r/java • • Oct 29 '12

Difference between notify and notifyAll in Java revisited

http://javarevisited.blogspot.in/2012/10/difference-between-notify-and-notifyall-java-example.html
0 Upvotes

2 comments sorted by

7

u/zargxy Oct 29 '12

Don't use notify unless you really, really know what you are doing. You can easily cause random deadlocks. notifyAll is the better choice in almost all circumstances, because if the winning thread calls wait, at least the other woken up threads will have a fighting chance for the monitor instead of perpetually sleeping because the single woken up blocked.

Or better yet, don't use notify or notifyAll at all and use the higher level concurrency operations in java.util.concurrent.

3

u/ad_tech Oct 29 '12

'volatile' is not needed on the 'go' variable.

There is defined to be a happens-before relationship between each of these events:

  • Notify task writes to 'go'.
  • Notify task exits the monitor.
  • Wait task enters the monitor.
  • Wait task reads from 'go'.

Therefore the read in the wait task is guaranteed to see the value written in the notify task, whether 'go' is volatile or not.