Synchronized vs ReentrantLock in Java

Synchronized, ReentrantLock and AtomicInteger are used in many projects to help solve concurrency issue and thread safety. The post will compare Synchronized and ReentrantLock.

When working on multi-threaded programming, we use synchronized for thread safety a lot. However, the builtin synchronized has some limits, and then Lock interface and its implementations comes up. ReentrantLock implements Lock interface, and allows the lock holder to enter blocks even after it has obtained the lock by entering other blocks of code.

Similarity

Both can provide visibility and orderings guaranteed as implicit lock.

Difference

  1. Java builtin synchronized has those optimizations: lock coarsening, biased locking (see below) and the potential for lock elision via escape analysis, which aren’t currently implemented for ReentrantLock in Java 6/7.
  2. ReentrantLock can check if a lock is being held, and can timeout while waiting for lock as it provides a tryLock() method, which acquires lock only if its available or not held by any other thread.
  3. ReentrantLock has ability to lock interruptibly as it provides lockInterruptibly() method which can interrupt thread when it is waiting for lock.
  4. ReentrantLock provides API to get List of waiting threads for lock.
  5. ReentrantLock can create fair lock which grants access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order.

ReentrantLock has many advantages over synchronized (see above).

Disadvantages of ReentrantLock

  1. ReentrantLock needs to wrap lock acquisitions in a try/finally block while synchronized does not need to.
  2. A developer needs to take care of acquiring and releasing lock, and may forget to release the lock in finally block which will cause the issue.

When to use

  1. If you implement a thread that traverses a linked list, locking the next node and then unlocking the current node, consider using ReentrantLock.
  2. If you have the situation like lock coarsening, biased locking and the potential for lock elision via escape analysis, consider using synchronized.

Performance comparison between ReentrantLock and Synchronized will be given in the future post.

java.util.concurrent.atomic.AtomicInteger provides a boolean variable which can be read and written atomically. It will be introduced in the future.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">