Search code examples
jvmreentrantlock

Is ReentrantLock is a light weight lock?


As we known, HotSpot VM has bias lock, spin lock, lightweight lock, heavyweight lock and so on,and ReentrantLock is implemented by AbstractQueuedSynchronizer(AQS)。 So ReentrantLock is a light weight lock in JVM?


Solution

  • These are different concepts.

    Spin lock, Biased lock, etc. are the names of algorithms/structures for implementing a locking mechanism (a mutex).

    In HotSpot terminology, biased lock, lightweight (thin) lock and heavyweight (inflated) lock are the possible states of a Java intrinsic monitor, i.e. a Java object that you can synchronize on using a synchronized keyword.

    In different moments of time, the same Java monitor can be in different states, e.g.

    1. On the first lock attempt the object is biased to a certain thread.
    2. Later, when another thread acquires the lock, the bias is revoked, and the monitor is successfully reacquired with a simple CAS - this will be a thin lock.
    3. Finally, when the a different thread attempts to acquite the monitor which is already locked, the lock is inflated.

    ReentrantLock is a Java class that implements the semantics of a mutex independently of Java intrinsic monitors. That is, the terms biased, thin and inflated do not appy to ReentrantLock.

    At the same time, ReentrantLock implementation also has multiple different paths. In a simple case, when there is no contention, acquiring ReentrantLock is a matter of a single CAS. In the contended case, ReentrantLock involves the waiting queue, and calls park to switch current thread from RUNNABLE to WAITING state. In this sense, the mechanism resembles JVM's thin and inflated locks. But again: since ReentrantLock is not an instrinsic monitor, it's not quite correct to compare it with JVM's lightweight and heavyweight locks.