Content: Use reentrantreadwritelock to wrap a map so that it can be safely shared among multiple read threads, and still avoid "read-write" or "write-write" conflicts. It is important to remember that the lock policy implemented by the read-write lock allows multiple read operations to be performed simultaneously, but only one write operation is allowed at a time.
public class Readwritemap<k, v> {private final map<k, v> map;private final readwritelock lock = new REENTRANTR Eadwritelock ();p rivate final Lock r = Lock.readlock ();p rivate final Lock w = lock.writelock ();p ublic Readwritemap (map< K, v> map) {this.map = map;} Public V put (K key, V value) {w.lock (); System.out.println ("Get write lock"); try {return map.put (key, value);} finally {w.unlock (); SYSTEM.OUT.PRINTLN ("Release write Lock");}} Public V get (K key) {R.lock (); SYSTEM.OUT.PRINTLN ("Get read lock"); try {return map.get (key);} finally {r.unlock (); SYSTEM.OUT.PRINTLN ("release read Lock");}} public static void Main (string[] args) throws Interruptedexception {final Map<integer, string> Map = new hashmap< Integer, String> (), Final Readwritemap<integer, string> readwritemap = new Readwritemap<integer, String> (map); Executorservice Executorservice = Executors.newcachedthreadpool (); for (int i = 0; I <=; i++) {final int tmp = I;exec Utorservice.execute (New Runnable () {@Overridepublic void run () {ReadwritemaP.put (TMP, tmp+ "");}); if ((i & 1) = = 1) {Executorservice.execute (new Runnable () {@Overridepublic void run () {System.out.println (Readwritema P.get (New Random (). Nextint (6));}});}} Executorservice.shutdown ();}}
Java uses a read-write lock to wrap a map