Arijeet Saha
Arijeet Saha

Reputation: 1168

How does JVM make sure only one thread can acquire the lock of an object?

Most of us know that whenever thread accesses a synchronized block of a object, JVM gives the lock of that object to the thread. How does JVM make sure that only one thread can have access to a lock of an object?

Upvotes: 3

Views: 909

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 61969

The JVM uses some locking feature provided by the operating system, like a semaphore object. So the question now becomes how the operating system does it.

Usually there is hardware support for these things. The CPU may offer a compare-and-set instruction which, while executing, sets a pin of the CPU (useful in multi-CPU architectures) or an internal line of the CPU (for single-CPU multicore architectures) which tells other hardware that the memory location currently formed on the address bus is not to be altered by anyone else. So, the hardware architecture guarantees the atomicity of this instruction.

Once you have a guaranteed-atomic compare-and-set instruction, the rest is relatively easy: the lock object has a flag; the thread wishing to acquire the lock performs a compare-and-set instruction on that flag with a value of 1; if the result of the comparison is true, then the value was already 1, so some other thread already had the lock. If the result is false, then the value was not 1, so the current thread may consider itself to be the owner of the lock now.

If the operating system cannot acquire a lock on behalf of a thread, then it places the thread in a "waiting for lock" state, in which the thread will stay until the lock gets released.

Upvotes: 3

Andrey E
Andrey E

Reputation: 866

JVM uses Monitor pattern for this purposes.

http://en.wikipedia.org/wiki/Monitor_(synchronization)

Upvotes: 1

Related Questions