Can someone explain the various differences between various synchronization methods in Java?
So really I wanted to know what are the different Java sync options commonly used and how they map to "traditional"/theoretical Mutexs, Semaphores, Locks, and Monitors.
Cheers!
I'll give a brief clarification of each:
tryLock
which only attempts to take the lock if it's free, otherwise returns immediately. Locks need to be unlocked explicitly.wait / notify
is roughly equivalent to the concept of condition variables. Similarly, they must be protected by a synchronized block and only work correctly if they are called when a lock is held on the object being used as a monitor.Java has native support of threading and synchronization. The native (or low-level) way to synchronize threads is using synchronized blocks and methods ( == critical section), wait()
and notify()
.
This technique allows you to do everything you want but unfortunately the way is sometimes pretty verbose. Doug Lea developed the concurrency package initially under Apache project. Then this package was adopted by Sun Microsystems. This package provides more convenient API.
Take a look on this article for more details: http://docs.oracle.com/javase/tutorial/essential/concurrency/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With