Search code examples
javamultithreadinglockingdeadlockreentrantreadwritelock

ReentrantReadWriteLock: what's the difference between ReadLock and WriteLock?


What I know is:

  • ReadLock and WriteLock affect each other somehow
  • WriteLock is just like synchronized
  • ReadLock seems cannot work alone

Solution

  • readLock.lock();

    • This means that if any other thread is writing (i.e. holds a write lock) then stop here until no other thread is writing.
    • Once the lock is granted no other thread will be allowed to write (i.e. take a write lock) until the lock is released.

    writeLock.lock();

    • This means that if any other thread is reading or writing, stop here and wait until no other thread is reading or writing.
    • Once the lock is granted, no other thread will be allowed to read or write (i.e. take a read or write lock) until the lock is released.

    Combining these you can arrange for only one thread at a time to have write access, but as many readers as you like can read at the same time except when a thread is writing.

    Put another way. Every time you want to read from the structure, take a read lock. Every time you want to write, take a write lock. This way whenever a write happens no-one is reading (you can imagine you have exclusive access), but there can be many readers reading at the same time so long as no-one is writing.