Write lock (ReentrantReadWriteLock with)

Key:

  1, shared read lock

  2, exclusive write locks

  3, exclusive write lock

 

Downgrade lock : write lock will be downgraded to a read lock. (First obtain a write lock, and then acquire a read lock, then release the write lock, and finally release the read lock)

Causes degradation lock: For performance reasons, under normal circumstances, the action will be locked, accurate to a specific block of statements in the statement block between two locks, it is possible to perform alternately thread, the thread causing safety problems.

the solution:

  1, the lock scope.

  2, the use of lock downgrade.

 

Why do we need to downgrade locks: 

Pseudocode: 
    w.lock (); // write lock 
    writeSomeDate (); // modify certain data 
    w.unlock (); // write lock release 

    r.lock (); // read lock 
    readSomeDate (); // Gets a data 
    r.unlock (); // read lock is released 

at this time, access to data when there is thread-safety issues. 


The revised code is: 
    w.lock (); // write lock 
    writeSomeDate (); // modify certain data 
    r.lock (); // read lock 
    w.unlock (); // release write lock 
    readSomeDate () ; // get a data 
    r.unlock (); // release read lock 
to read lock locking action, to put in writing before the release of the lock, the lock can be downgraded to a read lock.

  

Guess you like

Origin www.cnblogs.com/chen--biao/p/11366952.html