I am new to multithreading and I am attempting to implement a unbounded queue. I know that notifyAll wakes up all the threads that are waiting on the object's monitor. But what happens if I return object immediately after waking up the threads.
Will this cause issues, i.e T2 has the lock and is in the synchronized block whilst T1 (original thread) is returning the object after releasing the lock? As far as I understand, because the state is not being changed, it should be okay.
The code is as following:
public <T> T remove(SomeObj someObj) throws InterruptedException {
synchronized (obj) {
while(queue.isEmpty()) {
obj.wait();
}
//some calculation here
T foo = someObj.getTValue();
queue.remove(foo);
return foo;
}
}
public <T> void add(T foo) {
synchronized (obj) {
queue.add(foo);
obj.notifyAll();
}
}