Differences between synchronized and ReentrantLock in Java
Java 5 introduces the Lock interface to provide more efficient and finer control over resource locking. ReentrantLock is a common Lock implementation that provides Lock with the same basic behavior and semantics as synchronized, but with advanced features such as lock polling, wait for a lock of a given duration, and interruptable wait for a lock. In addition, it offers much better performance in highly competitive environments.
What is a reentrant lock? Simply that there is a collection count associated with the lock, and if the thread that holds the lock acquires it again, the data reflects the increase, and then the lock needs to be released twice to actually unlock. This is analogous to synchronized semantics; if a thread enters a synchronous block protected by a monitor that is already owned by the thread, the thread will be allowed to continue functioning, and the lock will not be released when the thread exits the second (or subsequent) synchronized block, it will only be released when it exits the first synchronized block into which he entered under the protection of the monitor.
Lock lock = new ReentrantLock();
lock.lock();
try {
// update object state
}
finally {
lock.unlock();
}
- The ReentrantLock implementation is much more competitively scalable than the synchronized implementation. This means that when many threads are trying to acquire a lock, the overall throughput is usually better for ReentrantLock than synchronized. The JVM takes less time to queue threads and more time to execute itself.
- ReentrantLock (like other Lock implementations) must release the lock in the finally block (otherwise, if the protected code had thrown an exception, the lock would not have been released). By using synchronization, the JVM ensures that the lock is automatically released.
In summary, we can say that when there is no or very little lock contention, synchronized may be faster. If there is a noticeable contention for access to a resource, then ReentrantLock is likely to give some advantage.
Read also:
Comments
Post a Comment