Sunday, March 27, 2016

Explicit Locking

Before java 5, we had to use synchonized keyword to lock an execution. This mechanism had couple of disadvantages
1. There was  no way to separate out read and write of an object with synchonized mechanism. Ideally in many scenarios, allowing multiple threads to read an object is harmless.

2. For time out, we needed wait/notify mechanism along with synchronized  .

3.There was no way to "attempt" to acquire a lock without waiting for other thread to release the
  relevant lock.

Java  5 has introduced two interfaces java.util.concurrent.locks.Lock and java.util.concurrent.locks.ReadWriteLock  . Though internal mechanism,memory access to perform actions on an shared object in a multi-threaded environment is same with old synchronized way, Lock and ReadWritLock provides  more functionalities/flexibility on performing actions on a shared object.

Classification of explicit locking:

1. Lock : This interface provides basic mechanisms to acquire and release lock, It stands out from its cousin "synchronized" by providing non-blocking and interruptible  locking.
Few implementations of Lock: ReentrantLock, ReadLock,WriteLock


2. ReadWriteLock:  ReadWriteLock maintains  a pair of associated locks, one for read and another for write.  The readLock can be hold by multiple threads to read, but writeLock is exclusive.
ReentrantReadWriteLock is an implementation of ReadWriteLock.









No comments:

Post a Comment