Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions will BlockingQueue.take throw interrupted exception?

Let us suppose that I have a thread that consumes items produced by another thread. Its run method is as follows, with inQueue being a BlockingQueue

boolean shutdown = false;
while (!shutdown) {
    try {
        WorkItem w = inQueue.take();
        w.consume();
    } catch (InterruptedException e) { 
        shutdown = true;
    }
}

Furthermore, a different thread will signal that there are no more work items by interrupting this running thread. Will take() throw an interrupted exception if it does not need to block to retrieve the next work item. i.e. if the producer signals that it is done filling the work queue, is it possible to accidentally leave some items in inQueue or miss the interrupt?

like image 616
Ryan Avatar asked Dec 24 '09 03:12

Ryan


People also ask

What exception is thrown when a thread is interrupted?

An InterruptedException is thrown when a thread is interrupted while it's waiting, sleeping, or otherwise occupied. In other words, some code has called the interrupt() method on our thread. It's a checked exception, and many blocking operations in Java can throw it.

What is use of interrupted exception?

Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.

What happens if the current thread has interrupted by another thread in thread interrupted exception?

If the target thread does not poll the interrupted status the interrupt is effectively ignored. Polling occurs via the Thread. interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

Should we catch interrupted exception?

If an InterruptedException is caught it means that the Thread. interrupt() method is called by some code, somewhere, on the currently running thread of the program. As a matter of fact, the only thing that can interrupt a thread is a call to Thread.


1 Answers

A good way to signal termination of a blocking queue is to submit a 'poison' value into the queue that indicates a shutdown has occurred. This ensures that the expected behavior of the queue is honored. Calling Thread.interupt() is probably not a good idea if you care about clearing the queue.

To provide some code:

boolean shutdown = false;
while (!shutdown) {
    try {
        WorkItem w = inQueue.take();
        if (w == QUEUE_IS_DEAD)
          shutdown = true;
        else
          w.consume();
    } catch (InterruptedException e) { 
        // possibly submit QUEUE_IS_DEAD to the queue
    }
}
like image 165
Kevin Day Avatar answered Oct 19 '22 23:10

Kevin Day