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
- 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 forReentrantLock
in Java 6/7. ReentrantLock
can check if a lock is being held, and can timeout while waiting for lock as it provides atryLock
() method, which acquires lock only if its available or not held by any other thread.ReentrantLock
has ability to lock interruptibly as it provideslockInterruptibly
() method which can interrupt thread when it is waiting for lock.ReentrantLock
provides API to get List of waiting threads for lock.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
ReentrantLock
needs to wrap lock acquisitions in a try/finally block while synchronized does not need to.- 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
- If you implement a thread that traverses a linked list, locking the next node and then unlocking the current node, consider using
ReentrantLock
. - 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.