English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The difference between ReentrantLock and synchronization in Java

There are two methods to lock shared resources using multiple threads. One is the reentrant lock (Or ReadWriteLock), and the other is by using the Synchronized method.

Java 5The ReentrantLock class is provided in the Java concurrency package. 

It is the implementation of the Lock interface. According to java docs, the implementation of the Lock interface provides a wider range of operations than those that can be obtained by using synchronized methods.

NumberKeyReentrant lockSynchronized
1
Obtain lock 
The ReentrantLock class provided by the ReentrantLock classlock()The method to obtain the shared resource lock through threads 
You only need to write the synced keyword to get the lock  
2
Release lock 
To release the lock, the programmer must callunlock()Method
Implicit completion 
3
 Interruptibility
The lockInterruptible() method can be used to interrupt a thread  
There is no way to interrupt a thread
4
Fairness 
The constructor of this class has a fairness parameter. If it is set to true, the lock will be granted to the one who has been waiting the longest *Thread access permission

Lock does not guarantee any specific access permission
5
Lock release order 
Locks can be released in any order 
Locks should be released in the order of obtaining the lock 

ReentrantLock example

public class ReentrantLockExample implements Runnable{
   private Lock lock = new ReentrantLock();
   @Override
   public void run() {
      try {
         lock.lock()
         //Lock some resources
      }
      catch (InterruptedException e) {
         e.printStackTrace();
      }
      finally {
         lock.unlock();
      }
   }
}

SynchronizedLock example

public class SynchronizedLockExample implements Runnable{
   @Override
   public void run() {
      synchronized (resource) {
         //Lock some resources
      }
   }
}