Read-Write Lock interface: Readwritelock, its specific implementation class is: Reentrantreadwritelock
Usage scenarios:
For a resource, reading can coexist, read and write cannot coexist, and write cannot coexist.
Lock downgrade: Change from write lock to read lock;
Lock Upgrade: Change from read lock to write lock.
Reentrantreadwritelock does not support lock escalation, support lock demotion
New Reentrantreadwritelock (); Rtlock.readlock (). Lock (); System.out.println ("Get readlock.") ); Rtlock.writelock (). Lock (); System.out.println ("blocking");
Will deadlock
New Reentrantreadwritelock (); Rtlock.writelock (). Lock (); System.out.println ("Writelock"); Rtlock.readlock (). Lock (); System.out.println ("get read lock");
No deadlock.
Case Application:
ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.concurrent.locks.ReadWriteLock;ImportJava.util.concurrent.locks.ReentrantReadWriteLock; Public classCachedemo {/*** Cache, here is assumed to store about 1000 cache objects, according to the default load factor of 0.75, the capacity = 750, the estimated length of each node list is 5 * Then the array length is about: 150, and the rain set the map size is generally 2 index, the most recent number is: 12 8*/ Privatemap<string, object> map =NewHashmap<> (128); PrivateReadwritelock RWL =NewReentrantreadwritelock (); Public Static voidMain (string[] args) {} Publicobject get (String ID) {Object value=NULL; Rwl.readlock (). Lock ();//First, read the lock, from the cache to fetch Try{Value=map.get (ID); if(Value = =NULL){//If a read lock is not released in the cache, the write lockrwl.readlock (). Unlock (); Rwl.writelock (). Lock (); Try{ if(Value = =NULL){//prevent multiple write threads from repeating query assignmentsValue = "Redis-value";//at this point you can go to the database to find, here is a simple simulation} rwl.readlock (). Lock (); //read lock Downgrade write lock, do not understand the principle of the above lock demotion and to keep the reading of data atomic explanation}finally{rwl.writelock (). Unlock ();//Release Write lock } } }finally{rwl.readlock (). Unlock ();//finally release the read lock } returnvalue; }}
If you do not use the lock demotion feature, such as releasing a write lock, and then obtaining a read lock, in this get process, there may be other threads competing to write lock or update data is the data obtained by other thread updates, may cause data pollution, that is, the problem of dirty read.
Read/write locks in Java