I would like to have a SynchronousQueue
where I insert elements from one thread with put()
, so the input is blocked until the element is taken in another thread.
In the other thread I perform lots of calculations and from time to time want to check if an element is already available, and consume it. But it seems that isEmpty()
always returns true, even if another thread is waiting at the put()
call.
How on earth is this possible? Here is the sample code:
@Test
public void testQueue() throws InterruptedException {
final BlockingQueue<Integer> queue = new SynchronousQueue<Integer>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (!queue.isEmpty()) {
try {
queue.take();
System.out.println("taken!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// do useful computations here (busy wait)
}
}
});
t.start();
queue.put(1234);
// this point is never reached!
System.out.println("hello");
}
EDIT: Neither isEmpty() nor peek() work, one has to use poll(). Thanks!