public class QueueCheck {
Queue queue;
public Integer getNextInt() {
Integer retVal = null;
synchronized (queue) {
try {
while (queue.isEmpty()) {
queue.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (queue) {
retVal = queue.poll();
if (retVal == null) {
System.err.println("retVal is null");
throw new IllegalStateException(); }
}
return retVal;
}
}
In the above code Queue is used as object monitor to handle
concurrency issues. But it may not behave correctly in a multithreading scenario.
There are two separate synchronized blocks in above code. In case
two threads are woken up simultaneously by another thread, both
threads will enter one after in the second synchronized block.
Only one of the two threads will get new value from the queue and
make it empty. The second thread will poll on an empty queue and it
will not get any non-null return value.
https://www.geeksforgeeks.org/thread-safety-and-how-to-achieve-it-in-java/