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

2

7

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?

Arbitral answered 1/5, 2013 at 6:4 Comment(0)
G
11

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)

Gaucherie answered 1/5, 2013 at 6:9 Comment(0)
S
2

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;
Steinke answered 1/5, 2013 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.