Search code examples
javamultithreadingjava.util.concurrent

Query regarding read-write locks


I am delving on the java concurrent APIs and trying to understand the usefulness of read-write locks. The javadoc says that a readwrite block maintains a pair of locks, one for read and the other for write operations. While the write lock is exclusive access by a thread, multiple threads can acquire the read lock. So if in the read section all we are doing is read operations and we are anyways providing multiple threads access, what is the need to have the readlock in the first place ? Is there a scenario when the readwrite lock is actually useful?


Solution

  • .... what is the need to have the readlock in the first place

    While reading, you need to prevent a writer acquiring the lock ... until all readers have finished. But it is OK for another reader to acquire the lock.

    While writing, you need to prevent a reader acquiring the lock ... until the writer has finished.

    (In other words, there can be one writer, OR multiple readers holding locks ... but not both.)

    For the purposes of describing this, it is helpful to describe the behaviour as being two locks. What actually happens under the hood ... is implementation specific.


    Is there a scenario when the readwrite lock is actually useful?

    Well yea. In any scenario where you can distinguish between threads that require shared read-only access and those that require exclusive read-write (or write-only), a ReadWrite lock allows more concurrency than a simple Lock or a primitive mutex.