ReadWriteLock Interface in Java
A lock is a device for commanding access to an assigned resource by multiple threads. Usually, a lock grants exclusive access to a shared resource: just one thread at a flash can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. Though, some locks may allow side-by-side access to a shared resource, as the read lock of a ReadWriteLock.
ReadWriteLock is an interface. ReadWriteLock is implemented by ReentrantReadWriteLock Class which is in java.util.concurrent.locks package. So, to use a ReadWriteLock we have to use ReentrantReadWriteLock.
A java.util.concurrent.locks.ReadWriteLock is a high-level thread lock tool. It allows various threads to read a specific resource but allows only one to write it, at a time.
The approach is, that multiple threads can read from a shared resource without causing concurrency errors. The concurrency errors first occur when writes and reads to a shared resource occur simultaneously, or if multiple writes take place simultaneously.
Read lock and Write lock which allows a thread to lock the ReadWriteLock either for reading or writing.
- Read lock: If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data.
- Write Lock: If no threads are writing or reading, only one thread at a moment can lock the lock for writing. Other threads have to wait until the lock gets released. It means, only one thread can write the data at the very moment, and other threads have to wait.
Methods: There are two methods that ReadWritelock provides:
- Lock readLock()
- Lock writeLock()
Their work is similar to their name. readLock() used to acquire the lock while reading:
Lock readLock = rwLock.readLock();
Use the read lock over a code block that performs read operation:
And, writeLock() used to acquire the lock while writing:
Lock writeLock = rwLock.writeLock();
Use write lock over a code block that performs write operation:
Element by thread main is added Element by thread main is added Element by thread main is added Elements by thread main is printed Printing the last element : Hello
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.