ReentrantReadWriteLock the lock downgrade

Lock downgrade refers to the write lock downgraded to a read lock.

Because read locks and read locks are not mutually exclusive, if a write lock and the read lock or a write lock and write lock will mutually exclusive, so by the write lock into a read lock on the downgrade of.

If the current thread has a write lock, then released , and finally re- acquire a read lock , and this is not able to call it a lock downgrade.

Lock downgrade refers hold on (currently owned) write locks , and then get to read lock , then release (previously useful) write lock process.

The following example is given of a lock downgrade, when the data changes, isUpdate variable is set to false, all this time threading all readwrite () method can perceive changes, but only one thread can obtain a write lock , other threads It is blocked in the read and write locks on the lock () method; the current thread to acquire a write lock after the completion of data preparation, and then get a read lock , then release the write lock , complete lock downgrade .

 

In order to ensure the visibility of data , if the current thread does not get a read lock but released directly write lock, assuming that there is another thread T to obtain a write lock and modify the data, then the current thread can not perceive thread T data update; however If the current thread to acquire a read lock, the thread T will be blocked until the current thread uses the data and then cast a read lock, write lock thread T in order to obtain data updates.

 

Explained with the following code, if the note 2 and the comments do not increase the read lock acquisition and release 6 (i.e. 2 // and // are commented 6), the put operation is completed the current thread Notes 1, annotate 3 write lock release operation at this time if there is another thread to acquire a write lock and modify (ie operation Note 1), the thread can not get a read lock on the current perception, conducting Note 4 and Note 5 occurs during operation thread safety issues.

If coupled with Note 2 and Note 6, due to the read lock and write between locks are mutually exclusive , and when the write lock release, due to the presence of 2 comments read lock, the new thread, and can not obtain a write lock , this time to ensure the thread safety .

 

 

 

Source: https://blog.csdn.net/u010512429/article/details/80011239

Guess you like

Origin www.cnblogs.com/theRhyme/p/9543140.html