i have two methods to add and remove elements from a circular buffer
the first implementation :
synchronized void add(byte b) throws InterruptedException {
if(availableObjects == size) wait();
buffer[(tail+1)%size] = b ;
tail++;
availableObjects++;
notifyAll();
}
synchronized byte remove() throws InterruptedException {
if(head==tail) wait();
Byte element = buffer[head%size];
head ++ ;
availableObjects--;
notifyAll();
return element;
}
and the second implementation :
private final Object addLock= new Object ();
private final Object removeLock=new Object ();
void add (byte b) throws InterruptedException{
synchronized (addLock){
while (availaibleObjects.get () == size) addLock.wait();
buffer [tail]= b;
tail = [tail + 1) % size;
availaibleObjects.incrementAndGet();}
synchronized (removeLock){ // why we added this block ?
removeLock.notifyAll();}
}
byte remove () throws InterruptedException{
byte element;
synchronized (removeLock){
while (availaibleObjects.get () == 0) removeLock.wait() ;
element = buffer[head] ;
head=(head + 1) % size;
availaibleObjects.decrementAndGet();}
synchronized (addLock){ // why we added this block ?
addLock.notifyAll();}
return element;}
my question is why in the second implementation of the methods we added a second synchronized block ?
- from the first implementation i get that two threads cannot add and remove at the same time .
- from the second implementation two threads can add and remove at the same time but i don't understand why we added the blocks :
synchronized (removeLock){ // why we added this block ?
removeLock.notifyAll();}
synchronized (addLock){ // why we added this block ?
addLock.notifyAll();}
return element;}
synchonizedblock in order to do anotifyAll()andwaitcalls.notifyAll()into a synchronized block ? we could've done that in the first block