![]() |
VOOZH | about |
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.
Rules:
Read lock and Write lock which allows a thread to lock the ReadWriteLock either for reading or writing.
Methods: There are two methods that ReadWritelock provides:
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:
Implementation:
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