Ch.06 – ReadWrite Lock

Published by

on

The idea behind ReadWriteLock is that allowing the Read operation to be much more flexible which wouldn’t be affected from other Reader thread.

  • When Reader thread tries to acquire lock
    • If a Writer thread is writing, wait.
    • If another Reader thread is reading, do not wait
  • When Writer thread tries to acquire lock
    • If another Writer thread is writing, wait
    • If a Reader thread is reading, wait

Example


The meaning of Lock

  • Using synchronized keyword acquires instance lock
    • No multiple threads can acquire this instance lock.
    • It is a physical lock provided by Java
  • Programmer can create a logical lock, just as Read lock and Write lock from the above example code(ReadWriteLock.java), but the physical lock that is being used in there is just one. Which is the instance lock of ReadWriteLock.

ReentrantReadWriteLock

  • ReentrantReadWriteLock implements ReadWriteLock and has ReadLock and WriteLock in itself.
    • Usage
      • lock.readLock();
        lock.writeLock();
  • The parameter when creating ReentrantReadWriteLock is for deciding the order of lock acquiring to be fair or not.
    • If true, thread that has been waiting longer is likely to acquire lock on the next turn.
  • ReentrantReadWriteLock class’s lock is possible to reentrant. Which means Reader thread can reenter to acquire Write lock and vise versa.

Reference

Leave a comment