0

While going through the javadoc for the notifyAll() method under Object class came through the following lines:

If the current thread is interrupted by any thread before or while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

The point is:

the current thread is interrupted while it is waiting

What does this means? Can a thread be interrupted while it is waiting? If yes, why? What is the use of it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Abhishek
  • 55
  • 2
  • 2
  • 8

2 Answers2

2

A thread can be interrupted while waiting if another thread calls:

waitingThread.interrupt();

This can happen if you do it yourself of course but also if you use a framework to manage your threads, typically an executor service, and call some of the methods that interrupt the underlying threads (e.g. shutdownNow or if you call future.cancel(true); on the Future returned by the submit method).

The interruption mechanism is how Java enables one thread to tell another one to stop what it is doing and is therefore extremely useful.

assylias
  • 321,522
  • 82
  • 660
  • 783
2

The meaning of "thread getting interrupted" in Java means that the thread's interrupted flag has been set, nothing more. However, most methods of the JDK which make the thread wait will immediately find out about this and exit the wait state, throwing an InterruptedException. Such is the case with the methods you have been reading about.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436