Why can't notifyAll() be used in a Thread instance? Why can't notifyAll() be used in a Thread instance? multithreading multithreading

Why can't notifyAll() be used in a Thread instance?


It sounds like the SONAR message you're seeing is this one:

Methods "wait(...)", "notify()" and "notifyAll()" should never be called on Thread instancessquid:S2236

Sonar has a detailed explanation of this:

On a Thread instance, the methods wait(...), notify() and notifyAll() are available only because all classes in Java extend Object and therefore automatically inherit the methods. But there are two very good reasons to not call these methods on a Thread instance:

Doing so is really confusing. What is really expected when calling, for instance, the wait(...) method on a Thread? That the execution of the Thread is suspended, or that acquisition of the object monitor is waited for?

Internally, the JVM relies on these methods to change the state of the Thread (BLOCKED, WAITING, ...), so calling them will corrupt the behavior of the JVM.

Likewise, the advice given in the Java API is:

It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Internal thread management is done by locking on thread objects. If your own application code locks on threads you may get unexpected or confusing behavior. For instance, when a thread terminates it sends a notification to every thread waiting on it.

In trying to assess the potential for problems I'd look for cases where a thread could receive a notification in error or miss out on a notification due to being used as a lock for application code and as a lock for internal JVM code. (This seems like it could be tedious.) Depending on the code I'd also look for possible consistency problems due to locking on threads as opposed to locking the data structures accessed by threads, and assess whether the locking scheme makes sense. If the code is subclassing Thread I would want to check out if threads get pooled and how.

Mostly this message would make me think, if this code is doing this one bad thing then what else is it possibly doing wrong? A SONAR message is just a hint that it found a bad smell in the code so that you can investigate and see how significant the problem is.


You shouldn't be sub-classing Thread. Doing so opens up a host of reasonably well know problems. Using wait/notifyAll is not a great choice since the concurrency libraries were added more than ten years ago but on Thread it is particularly bad because the Thread class also uses wait/notify for its own purposes.