Search code examples
javareflectionconcurrencylockingreentrantlock

How implementation of Re-entrant lock and Synchronization is different


As per java source code

ReentrantLock's lock(non-fair) is as below.

public boolean lock(){
      int c=getState();
      if(c==0){
         compareAndSetState(0,1);
      }
}
//getState method
public int getState(){
    return state;
}
public boolean compareAndSetState(int expected,int update){
    unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

and value of stateOffSet is offset of state in memory(using reflection).

what i can understand from above code is ,when we call lock.lock(),first value of state fields in checked in memory,if it is zero then only lock is given to calling thread.

so my question is what happens when we user Synchronized key word? does in Synchronized also some field of lock is checked and set?

one more doubt,somewhere I read reentrant lock allows multiple wait queue,what does that mean?don't we have just one queue for both?


Solution

  • reentrant lock allows multiple wait queue,what does that mean?

    It means that you can get more than one Condition object from an ReentrantLock object. That's useful when there is more than one reason why a thread would want to wait for something that is protected by the lock.

    A classic example would be a multi-producer, multi-consumer queue. You can have one Condition that consumers use to wait for the queue to become non-empty, and a different Condition that producers use to wait for it to become non-full. That's an optimization. It ensures that a producer will not wake up other waiting producers, nor will a consumer wake up other waiting consumers.

    The same optimization is not available if you protect the queue with synchronized blocks, because the o.wait() method provides no means for a thread to say what event it is waiting for.


    what happens when we usesynchronized key word

    The only things you can be sure of are what you read in the Java Language Specification: No two threads will be allowed to synchronize on the same object at the same time, memory visibility effects, etc.

    As for how it is implemented,... That will be different on different architectures and maybe on different operating systems. At the lowest level, it probably will be similar to how ReentrantLock works because most hardware architectures provide approximately one reasonable way to do it. But the details of mid-level APIs and libraries used by the synchronized implementation (if any) and the ReentrantLock implementation could be different. The only way to know for sure would be to examine the JVM and library source code.