In the pseudocode below I have a poll() function that gets called forever in the main thread. When I do this without the sleep() statement in poll(), only 2-3 items a minute get added to the queue by the other thread. Does this mean that polling blocks the put() statement?
How can I solve this problem?
public class Test extends Thread{
private LinkedBlockingQueue<Object> queue = null;
Test(){
queue = new LinkedBlockingQueue<Object>(10);
}
public void run(){
// Do stuff, get incoming object from network
queue.put(o);
}
public Object poll(){
Object o = queue.poll();
sleep(1000);
return o;
}
}
No,
LinkedBlockingQueueis fully reentrant and thepoll()method does not block theput(). However, thepoll()method returns immediately. You probably should be usingqueue.take()which waits for there to be an item in the queue instead of returning null if the queue is empty.Since you are constructing a constrained blocking queue of 10 entries, I guess that main is blocking on the
sleep()and the queue then fills up and slows down your program. You maybe should onlysleepif therepoll()returnsnulland sleep for a shorter amount of time.Edit: As @JohnVint mentioned in the comments, another alternative is to use the
poll(long, TimeUnit)method which will wait for an item to be added to the queue for the time period and returnsnullif the timer expires. That is a cleaner way to wait for something in the queue.