Java uses a read-write lock to wrap a map

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.