Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 868
Ratha Avatar asked May 01 '13 06:05

Ratha


2 Answers

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)

like image 160
Jeremy Unruh Avatar answered Nov 02 '22 23:11

Jeremy Unruh


Both the option to queue (offer) or dequeue (poll) elements from the queue have the option to set configurable time-out. Method javadocs below :

/**
 * Inserts the specified element into this queue, waiting up to the
 * specified wait time if necessary for space to become available.
 *
 * @param e the element to add
 * @param timeout how long to wait before giving up, in units of
 *        <tt>unit</tt>
 * @param unit a <tt>TimeUnit</tt> determining how to interpret the
 *        <tt>timeout</tt> parameter
 * @return <tt>true</tt> if successful, or <tt>false</tt> if
 *         the specified waiting time elapses before space is available
 * @throws InterruptedException if interrupted while waiting
 * @throws ClassCastException if the class of the specified element
 *         prevents it from being added to this queue
 * @throws NullPointerException if the specified element is null
 * @throws IllegalArgumentException if some property of the specified
 *         element prevents it from being added to this queue
 */
boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException;



/**
 * Retrieves and removes the head of this queue, waiting up to the
 * specified wait time if necessary for an element to become available.
 *
 * @param timeout how long to wait before giving up, in units of
 *        <tt>unit</tt>
 * @param unit a <tt>TimeUnit</tt> determining how to interpret the
 *        <tt>timeout</tt> parameter
 * @return the head of this queue, or <tt>null</tt> if the
 *         specified waiting time elapses before an element is available
 * @throws InterruptedException if interrupted while waiting
 */
E poll(long timeout, TimeUnit unit)
    throws InterruptedException;
like image 43
Scorpion Avatar answered Nov 02 '22 22:11

Scorpion