Open In App

Difference Between ReadWriteLock Interface and ReentrantReadWriteLock Class in Java

ReadWriteLock is an interface in java.  A ReadWriteLock allows us to add a thread-safety feature to a data structure while increasing throughput by allowing multiple threads to read the data concurrently and one thread to update the data exclusively.

ReadWriteLock is described in the java.util.concurrent.locks package, with ReentrantReadWriteLock is an implementation class. ReadWriteLock implementations assure that the memory synchronization effects of writeLock operations (as described in the Lock interface) also hold with respect to the associated readLock. So, we can create a ReadWriteLock like this:



ReadWriteLock rwlock = new ReentrantReadWriteLock();

An assured pair of locks are associated with ReadWriteLocks :

The read lock may be held at the same time by many reader threads, as long as there are no writers. And the write lock is exclusive. 



ReentrantReadWriteLock Class in java

ReentrantReadWriteLocks can be used to enhance concurrency in some uses of kinds of Collections. ReentrantReadWriteLock class is a useful one and only the collections are expected to be major, accessed by more reader threads than writer threads, and require operations with overhead that outweighs synchronization overhead.

The ReentrantReadWriteLock class has the following properties:

ReentrantReadWriteLock is described in the java.util.concurrent.locks package, with implemented interfaces are Serializable, ReadWriteLocks. We can create a ReentrantReadWriteLock like this: 

ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

The ReentrantReadWriteLock has two separate locks:

Lock r = rwl.readLock();
Lock w = rwl.writeLock();

Difference Between ReadWriteLock and ReentrantReadWriteLock

S. No. ReadWriteLock ReentrantReadWriteLock
1. ReadWriteLock is an interface. ReentrantReadWriteLock is a class.
2. ReadWriteLock implements ReentrantReadWriteLock class. ReentrantReadWriteLock implements ReadWriteLock interface, supporting similar semantics to ReentrantLock.
3. The ReadWriteLock interface defines locks similarly, that may be shared among readers but are exclusive to writers. Here, a single implementation, ReentrantReadWriteLock, is provided, since it covers most standard usage contexts. 
4. It is designed as a high-level locking mechanism that allows you to append thread-safety features to a data structure. Programmers may develop by their own implementations to cover nonstandard requirements.
Article Tags :