In C#, the lock
keyword is nice syntax for a try/catch
block and an instance of Monitor
.
In Java, what synchronization class is used user the hood of the synchronized
keyword?
Edit - I did some further poking - looks like it synchronized gets compiled to monitorenter/monitorexit bytecode ops. Is there a class that duplicated these semantics?
This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized , so only one thread can execute any of them at a time.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock.
No class is used - it is a language construct handled by the JVM.
However, Java 5 introduced java.util.concurrent.locks
where you have the Lock
interface and its multiple implementations. See the linked docs for sample usage.
The synchronized
keyword causes the entity it modifies to be synchronized with a lock internal to the JVM. There is no architected class for it, so far as I can recall, and it doesn't necessarily correspond to any specific OS construct.
However, there is a bytecode construct for the lock mechanism, used to enter/exit synchronized {}
blocks.
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