How long a blocking queue will wait for an element to dequeue?

Ratha picture Ratha · May 1, 2013 · Viewed 9.1k times · Source

I'm using a blocking queue implementaion in my program.I would like to konw how long the thread will wait for a element to dequeue.? My client thred polls fro response, my server thread offers message. My code is as follows;

private BlockingQueue<Message> applicationResponses=  new LinkedBlockingQueue<Message>();

client:

    Message response = applicationResponses.take();

server:

    applicationResponses.offer(message);

Will my client thread wait forever? i would like to configure that time..(eg: 1000ms)..is that possible?

Answer

Jeremy Unruh picture Jeremy Unruh · May 1, 2013

Yes it will wait forever until you can take an element. You should use poll(time, TimeUnit) if you want to have a max wait time.

Message response = applicationResponse.poll(1, TimeUnit.SECONDS);

See: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll(long,%20java.util.concurrent.TimeUnit)