oneat oneat - 7 months ago 42
Java Question

What does java.lang.Thread.interrupt() do?

Could you explain what

does when invoked?


Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. 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.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait()/Thread.sleep()
  • Most java.util.concurrent structures
  • Java NIO (but not and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.