Monitor Method Called On Thread
ID |
java.no_wait_notify_on_thread |
Severity |
critical |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports a call to wait(…), notify() or notifyAll() whose receiver’s declared type is
java.lang.Thread, or a subclass of Thread declared in the same file — including an
implicit-this call made from inside such a subclass.
The same calls on a plain Object used as a lock are the normal monitor idiom and are not
flagged.
Rationale
wait(…), notify() and notifyAll() belong to Object’s own monitor and are meant to be
called on whatever object is used as a lock for synchronization — not on the `Thread that
merely represents a unit of execution. The JVM uses that same monitor state internally to track
a thread’s own life cycle (BLOCKED, WAITING, …), so calling one of these methods directly
on a Thread instance can corrupt bookkeeping the caller never intended to touch.
Thread worker = new Thread(this::processQueue);
worker.start();
...
worker.wait(); // corrupts the JVM's own thread-state bookkeeping
Remediation
Use a dedicated lock object for coordination between threads, and reserve the Thread
instance itself for lifecycle operations such as start(), join() and interrupt():
private final Object lock = new Object();
Thread worker = new Thread(this::processQueue);
worker.start();
...
synchronized (lock) {
lock.wait();
}