3 ms·
The wait method can only be invoked when the object is locked (e.g. within a synchronized block). The method throws an IllegalMonitorStateException otherwise. T
by layer8 2y ago
The wait method can only be invoked when the object is locked (e.g. within a synchronized block). The method throws an IllegalMonitorStateException otherwise. This implies that the map access is protected by that lock. Entering the wait releases the lock, and leaving the wait reacquires the lock. Those lock operations also imply a happens-before ordering, meaning changes made to the map by another thread during the wait are guaranteed to become visible to the current thread.
The code is perfectly correct, and straightforward if you’re familiar with Java concurrency basics. Wait and notify were designed to be used in that way to wait for a condition. This is (or was) a common Java synchronization idiom:
https://wiki.sei.cmu.edu/confluence/display/java/THI03-J.+Always+invoke+wait%28%29+and+await%28%29+methods+inside+a+loop https://wiki.sei.cmu.edu/confluence/display/java/THI03-J.+Al...
https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html https://docs.oracle.com/javase/tutorial/essential/concurrenc...
Regarding the “small chance of a race”, the code’s whole purpose is to remove that race by synchronizing properly, which it does. The author presumably didn’t show the surrounding lock because it is implied by the wait, and because they were assuming their audience to be familiar with the idiom.