java - Should I Thread.currentThread.interrupt() before I throw an exception back? -
i implementing interface throws ioexception
. in implementation, call method can block, , therefore throw interruptedexception
.
context:
- i want end treatment if interrupted;
- this not thread created myself.
my current idea such (skeleton code):
@override public void implementedmethod() throws ioexception { try { methodthatblocks(); } catch (interruptedexception ignored) { thread.currentthread().interrupt(); throw new ioexception(); } }
is correct way? or should throw
, not .interrupt()
?
yes, should call interrupt() let calling code know thread has been interrupted. if don't it, since interruptedexception clears it, calling code have no way know interruption , won't stop running although should.
let me quote java concurrency in practice:
restore interrupt. cannot throw interruptedexception, instance when code part of runnable. in these situations, must catch interruptedexception , restore interrupted status calling interrupt on current thread, code higher call stack can see interrupt issued, 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(); } } }
Comments
Post a Comment