Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What primitive is used to implement the synchronized keyword?

When we use synchronized keyword in java, which synchronization primitive is used exactly? Lock, Semaphore, Monitor, Mutex ?

EDIT : How JVM implements the lock at the native level ?

like image 874
AllTooSir Avatar asked Mar 28 '13 14:03

AllTooSir


2 Answers

At bytecode level, java has monitorenter and monitorexit operations, documented in this page of The Java Virtual Machine Specification, with snippets pasted below (objectref is operand for the operation, taken from stack):

monitorenter snippet

Each object has a monitor associated with it. The thread that executes monitorenter gains ownership of the monitor associated with objectref. If another thread already owns the monitor associated with objectref, the current thread waits until the object is unlocked, then tries again to gain ownership. If the current thread already owns the monitor associated with objectref, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with objectref is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1.

monitorexit snippet

The current thread should be the owner of the monitor associated with the instance referenced by objectref. The thread decrements the counter indicating the number of times it has entered this monitor. If as a result the value of the counter becomes zero, the current thread releases the monitor. If the monitor associated with objectref becomes free, other threads that are waiting to acquire that monitor are allowed to attempt to do so.

So, "monitor" is the answer, and neither this, nor JLS referenced in NPE's answer specify what happens at native code level. If you have a specific platform (CPU and operating system) and a specfic JVM implementation (including version) in mind, you can of course either look at the JVM source (if it is an open source JVM), or ask here.

I also happened across this blog from 1997, which has more details.

like image 103
hyde Avatar answered Oct 26 '22 21:10

hyde


From the JLS (§17.1. Synchronization):

The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.

Thus "monitor" is the answer to your first question.

As to the second question, this is an unspecified implementation detail.

like image 33
NPE Avatar answered Oct 26 '22 22:10

NPE