Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the synchronized java keyword implemented?

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?

like image 734
Scott Weinstein Avatar asked Aug 15 '11 16:08

Scott Weinstein


People also ask

How is synchronized implemented in Java?

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.

How does synchronized keyword work in Java?

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.

How is thread synchronization implemented?

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.


2 Answers

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.

like image 186
Bozho Avatar answered Oct 10 '22 09:10

Bozho


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.

like image 44
Hot Licks Avatar answered Oct 10 '22 09:10

Hot Licks