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
synchronizedhas those optimizations: lock coarsening, biased locking (see below) and the potential for lock elision via escape analysis, which aren’t currently implemented forReentrantLockin Java 6/7. ReentrantLockcan 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.ReentrantLockhas ability to lock interruptibly as it provideslockInterruptibly() method which can interrupt thread when it is waiting for lock.ReentrantLockprovides API to get List of waiting threads for lock.ReentrantLockcan 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
ReentrantLockneeds 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.








