Difference between synchronized and reentrantlock? Pros and Cons [closed]

来源:互联网 发布:空军飞行员知乎 编辑:程序博客网 时间:2024/05/21 19:23

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

From: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html

Extended capabilities include:

  1. The ability to have more than one condition variable per monitor. Monitors that use the synchronized keyword can only have one. This means reentrant locks support more than one wait()/notify() queue.
  2. The ability to make the lock "fair". "[fair] locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order." Synchronized blocks are unfair.
  3. The ability to check if the lock is being held.
  4. The ability to get the list of threads waiting on the lock.

The disadvantages of reentrant locks are:

  1. Need to add import statement.
  2. Need to wrap lock acquisitions in a try/finally block. This makes it more ugly than the synchronized keyword.
  3. The synchronized keyword can be put in method definitions which avoids the need for a block which reduces nesting.
原创粉丝点击