Are read and write locks in ReentrantReadWriteLock somehow related?

不羁的心 提交于 2019-12-22 06:27:21

问题


Please explain me more the contract. I can't figure out if two locks contained in ReentrantReadWriteLock somehow related? Or these are just a bundle of two normal locks?


回答1:


If threads are waiting Read Lock it is shared but when thread wants to acquire write lock only that thread is allowed the access same as mutual exclusion.

So either one of operation is allowed .if lock is held by readers and thread request write lock no more readers are allowed to acquire read lock until thread which has acquired write lock release it.




回答2:


It allows multiple threads to read a resource concurrently, but requires a thread to wait for an exclusive lock in order to write to the resource.

Rules are:

  • Several readers can share the resource concurrently. If you have a read lock, you can safely acquire another read lock. The maximum count of shared locks is 1111 1111 1111 1111
  • If you have a read lock, you CANNOT acquire a write lock
  • If you have a write lock, you CANNOT acquire a read lock in any other thread.
  • A reader can access the resource when there are no writers active in any other thread.
  • If you have a write lock, you can acquire another write lock in the same thread. The maximum count of exclusive locks that a thread can own is 1111 1111 1111 1111
  • A writer can access the resource when no other reader or writer (from a different thread) is active.
  • Prefers writers over readers. That is, if a writer is waiting on the lock, no new readers from other thread are allowed to access the resource. Existing readers can continue to use the resource until they release the lock. This prevents so-called "writer starvation".
  • Allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible.

Internally the lock state (c) is maintained by an int value. In this case, since we have read and write locks, it is logically divided into two shorts: The lower one representing the exclusive (writer) lock hold count, and the upper the shared (reader) hold count.

Assuming current state of lock is c= xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy then Number of reader locks are the upper bits xxxx xxxx xxxx xxxx

Number of writer locks are the lower bits yyyy yyyy yyyy yyyy



来源:https://stackoverflow.com/questions/13091967/are-read-and-write-locks-in-reentrantreadwritelock-somehow-related

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!