3

I keep getting this exception inside of a synchronized block, in which I call wait on the same object I'm synchronized on. What does it mean for a thread to be interrupted first of all? secondly, what are normal scenarios where this would happen? any advice as to what could be going on or what I should do?

Tim
  • 4,295
  • 9
  • 37
  • 49

2 Answers2

3

The interrupt mechanism is used to inform a thread that it should terminate itself as soon as possible. This allows the interrupted thread to exit safely without leaving any data in an inconsistent state.

Moonbeam
  • 2,283
  • 1
  • 15
  • 17
  • For more information, I suggest reading Java Concurrency in Practice, especially the chapter "Cancellation and Shutdown." – Moonbeam Mar 11 '12 at 03:17
  • 1
    I would like to point out that interrupt doesn't necessarily mean to end the processing. It just sets a flag and throws InterruptedException. How the interrupted thread reacts is purely its problem. It can be used to shift processing states or as a restart initiator. It just tells the thread that something fundamental changed and that the current execution state might no longer be valid or useful or desirable or whatever. – Jakub Zaverka Mar 11 '12 at 03:35
3

What does it mean for a thread to be interrupted first of all?

It means that something has called Thread.interrupt() on the thread object. This sets the interrupted flag on the thread, and causes certain method calls to terminate with an exception.

Secondly, what are normal scenarios where this would happen?

It is typically used when a second thread wants to tell this thread to stop what it is doing. The call could be direct, or it could be done by a library method. For instance, ThreadPoolExecutor.shutdownNow() uses interrupts to (try to) terminate executing tasks.

Note that interrupting a thread does not guarantee to stop it. Indeed, barring the cases where an exception is thrown, the thread will only notice that it has been interrupted if it calls interupted() or isInterupted(). Even then, it could simply clear the flag and continue as if nothing has happened.

Any advice as to what could be going on or what I should do?

Take a look at what is "controlling" the thread that got interrupted.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216