Sunday, April 2, 2017

Limitation of synchronized keyword in Java

1. Synchronized keyword doesn't allow separate locks for reading and writing. As we know that multiple threads can read without affecting thread-safety of class, synchronized keyword suffer performance due to contention in case of multiple readers and one or few writer.

 2. If one thread is waiting for lock then there is no way to timeout, the thread can wait indefinitely for the lock.
 
3. On a similar note if the thread is waiting for the lock to acquired there is no way to interrupt the thread.
 
All these limitations of synchronized keyword are addressed and resolved by using ReadWriteLock and ReentrantLock in Java 5.

No comments: