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

前端 未结 5 629
庸人自扰
庸人自扰 2020-11-30 20:33

What I know is:

  • ReadLock and WriteLock affect each other somehow
  • WriteLock is just like synchronized
  • ReadLock
5条回答
  •  温柔的废话
    2020-11-30 21:09

    Using ReadWriteLock, you can improve performance of an application in which more reads are performed on a shared object than writes.

    ReadWriteLock maintains two locks for read and write operations. Only one lock either read or write can be acquired at the same time. But multiple threads can simultaneously acquire read lock provided write lock is not acquired by any thread.

    ReentrantReadWriteLock is an implementation of ReadWriteLock. It gives write lock to the longest waiting thread if multiple thread are not waiting for read lock. If multiple threads are waiting for read lock, read lock is granted to them.

    A reader which acquired read lock can reacquire read lock, similarly, writer can reacquire write lock and can acquire read lock also.

    See http://www.zoftino.com/java-concurrency-lock-and-condition-examples

提交回复
热议问题