Inspectopedia Help

'wait()' not called in loop

Reports calls to wait() that are not made inside a loop.

wait() is normally used to suspend a thread until some condition becomes true. As the thread could have been waken up for a different reason, the condition should be checked after the wait() call returns. A loop is a simple way to achieve this.

Example:

class BoundedCounter { private int count; synchronized void inc() throws InterruptedException { if (count >= 10) wait(); ++count; } }

Good code should look like this:

class BoundedCounter { private int count; synchronized void inc() throws InterruptedException { while (count >= 10) wait(); ++count; } }

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023