当前位置:网站首页>Synchronized and reentrantlock

Synchronized and reentrantlock

2022-07-06 00:37:00 InfoQ

synchronized  and  ReentrantLock  What's the difference? ?

synchronized:synchronized  An exclusive pessimistic lock , It's through  JVM  Realization ,synchronized  Only one thread is allowed to operate resources at the same time .

ReentrantLock:ReentrantLock  yes  Lock  One of the default implementations of , It is based on  AQS  Realized , The default is unfair , There's a  state  The status field is used to indicate whether the lock is occupied , If it is  0  It means that the lock is not occupied , When the thread  state  Change it to  1, It means that the thread has successfully obtained the lock , Other threads need to queue for locks .

  • synchronized  and  ReentrantLock  Both provide the function of lock
  • ReentrantLock  Can be set to fair lock , and  synchronized  You can't
  • ReentrantLock  Only code blocks can be decorated , and  synchronized  Can be used to modify methods 、 Decorate code blocks, etc ;
  • ReentrantLock  You need to manually lock and release the lock , The lock is not released , It will cause resources to be occupied and not be released , and  synchronized  There is no need to release the lock manually , from jvm Internal automatic locking and release lock
  • ReentrantLock  You can actively obtain information about whether the lock has been successfully obtained , and  synchronized  no way , It can be understood as black box method

Use

ReentrantLock Use :ReentrantLock  It's through  lock()  To get the lock , adopt  unlock()  Release the lock , Use the code :

Lock lock = new ReentrantLock();
try {
 lock.lock();
} finally {
 lock.unlock();
}

synchronized Use :

  • Directly decorated on the method declaration
  • Declared in a method block

The difference in principle

Synchronized from monitorenter Realization :

  • Each object has a lock monitor, When monitor It will be locked when occupied
  • If monitor The number of entries is 0, Then the thread enters monitor, Then set the number of entries to 1, This thread is monitor Owner
  • If monitor The number of entries is not 0, Indicates that a thread has entered monitor, Then the thread enters the blocking state
  • After thread execution , sign out monitor, Set the entry number to 0

ReenTrantLock from CAS+CLH Queue to implement :

  • CAS:Compare and Swap, Compare and exchange , This operation is an atomic operation
  • CLH queue : Two way acyclic linked list with leading node
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060033007242.html