I would like to make sure that my circular buffer is thread safe. I am using the buffer to store data streamed in over bluetooth, and at the same time I am using another thread to remove data and store in locally in an android device.
This is my current CircularBuffer using Semaphore. Is it possible to make it thread proof by simply adding synchronized to every method? That would be my preferred method.
public class CircularBuffer {
// private byte[][] data;
private int data[];
private int head;
private int tail;
private Semaphore readPermission;
public CircularBuffer(Integer number) {
// data = new byte[number][];
readPermission = new Semaphore(1);
data = new int[number];
head = 0;
tail = 0;
}
public boolean store(byte[] value) {
if (!bufferFull()) {
ByteBuffer bb = ByteBuffer.wrap(value);
// may need to be reversed
int intVal = bb.getShort();
Log.i("Buffer Input", "" + intVal);
// data[tail++] = value;
data[tail++] = intVal;
if (tail == data.length) {
tail = 0;
}
return true;
} else {
return false;
}
}
public int getSize() {
return tail - head;
}
public int read() {
Log.i("Buffer", "Taking");
if (head != tail) {
// byte[] value = data[head++];
int value=data[head++];
if (head == data.length) {
head = 0;
}
return value;
} else {
//return null;
return 0;
}
}
//Getting permission using a semaphore
public void getPermission(){
try {
readPermission.acquire();
} catch (InterruptedException e) {
Log.i("Buffer", "Interrupted Exception");
e.printStackTrace();
}
}
//Giving up permission using a semaphore
public void givePersmission(){
readPermission.release();
}
}
as you need only a mutual exclusive access synchronized is OK, but you do not need to use it on all the methods. Only the methods that really need to be synch,
If you use semaphore be sure you write exceètion safe code to be sure that you will release the semaphore whatever happens.
From this point of view a mutex is safer.