Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Thread.currentThread.interrupt() before I throw an exception back?

I am implementing an interface which throws IOException. In my implementation, I call another method which can block, and therefore throw InterruptedException.

Context:

  • I want to end the treatment if I am interrupted;
  • this is not a thread I created myself.

My current idea is to do as such (skeleton code):

@Override
public void implementedMethod()
    throws IOException
{
    try {
        methodThatBlocks();
    } catch (InterruptedException ignored) {
        Thread.currentThread().interrupt();
        throw new IOException();
    }
}

is that the correct way? Or should I just throw and not .interrupt()?

like image 966
fge Avatar asked Mar 24 '14 20:03

fge


People also ask

What does thread currentThread () interrupt do?

currentThread(). interrupt(); allows you to exit out of thread faster, hence when InterruptedException e is caught, the thread is stopped then and there.

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 does thread currentThread () return?

currentThread() method returns a reference to the currently executing thread object.

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

Yes, you should call interrupt() to let the calling code know that the thread has been interrupted. If you don't do it, since the InterruptedException clears it, the calling code will have no way to know about the interruption and won't stop running although it should.

Let me quote Java Concurrency in Practice:

Restore the interrupt. Sometimes you cannot throw InterruptedException, for instance when your code is part of a Runnable. In these situations, you must catch InterruptedException and restore the interrupted status by calling interrupt on the current thread, so that code higher up the call stack can see that an interrupt was issued, as demonstrated in Listing 5.10.

public class TaskRunnable implements Runnable {
    BlockingQueue<Task> queue;
    ...
    public void run() {
        try {
            processTask(queue.take());
        } catch (InterruptedException e) {
             // restore interrupted status
             Thread.currentThread().interrupt();
        } 
    }
}
like image 149
JB Nizet Avatar answered Oct 25 '22 04:10

JB Nizet