Domanda

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()?

È stato utile?

Soluzione

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();
        } 
    }
}

Altri suggerimenti

Of course not. The thread is already unblocked and running. In the code that is about to throw an exception. What would be the point?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top