JAVA concurrent Programming-read-write lock simulation cache system (11)

Source: Internet
Author: User

In multi-threading, in order to improve efficiency some shared resources allow multiple read operations at the same time, but only allow a write operation, such as a file, as long as its content is not changed to allow multiple threads to read at the same time, do not have to do an exclusive lock, exclusive locking is only required when writing, to ensure that other threads do not see the data This is the time to use a read-write lock.


/** * Simple read/write lock demo * @author Hejingyuan * */public class Readwritelocktest {public static void main (string[] args) {final Que Ue3 q3 = new Queue3 ();//create several threads for (int i=0;i<3;i++) {new Thread () {public void run () {while (true) {Q3.get ();}}}. Start (); new Thread () {public void run () {while (true) {Q3.put (New Random (). Nextint (10000));}}. Start ();}}} Class Queue3{private Object data = null;//share data, only one thread can write that data, but there can be multiple threads reading the data at the same time//read/write lock Readwritelock rwl = new Reentrantreadwritelock ();//Read data public void get () {Rwl.readlock (). Lock (); try {System.out.println ( Thread.CurrentThread (). GetName () + "be ready to read data!"); Thread.Sleep ((Long) (Math.random () *1000)); System.out.println (Thread.CurrentThread (). GetName () + "has read data:" + data);} catch (Interruptedexception e) {e.printstacktrace ();} Finally{rwl.readlock (). Unlock ();}} Write data public void put (Object data) {Rwl.writelock (). Lock (); try {System.out.println (Thread.CurrentThread (). GetName () + "Be ready to write data!"); Thread.Sleep ((Long) (Math.random () *1000)); this.data = Data System.out.println (Thread.CurrentThread (). GetName () + "have write data:" + data);} catch (Interruptedexception e) {e.printstacktrace ();} Finally{rwl.writelock (). Unlock ();}}}


Operation Result:

Thread-0 is ready to readdata!

Thread-2 is ready to readdata!

Thread-2have Read Data:null

Thread-0have Read Data:null

Thread-1 is ready towrite data!

Thread-1 have write data:1021

Thread-1 is ready towrite data!

Thread-1 have write data:2887

See here inevitably someone will ask, since the reading time can be more people visit, then why should read the lock?

A: Of course, to lock, or to read when writing, may not be correct - (Cannot read when writing)

read/write lock - Simulation Cache system implementation:


public class Cachedemo {private map<string, object> cache = new hashmap<string, object> ();p ublic static void M Ain (string[] args) {}//definition read-write lock private Readwritelock RWL = new Reentrantreadwritelock ();//Read data, use read lock public  Object GetData (String key) {//Add read lock Rwl.readlock (). Lock (); Object value = Null;try{value = Cache.get (key); if (value = = null) {// Release read lock Rwl.readlock (). Unlock ()//Plus write lock Rwl.writelock (). Lock () try{//assumes that three threads are simultaneously acquiring a write lock, we know that only the first thread can get                    // Then the other two threads only wait, if the first thread after the process is finished, just two threads can get a write lock,                    //And then can then modify the data (Assignment). So Plus judge!if (value==null) {//Why do you still have to judge? Value = "AAAA";//actually go to Querydb ();}} finally{//Release write lock Rwl.writelock (). Unlock ();} Rwl.readlock (). Lock ();}} Finally{rwl.readlock (). Unlock ();} return value;}}


Summarize:

the function of read and write locks is that when we add a write lock, other threads are blocked, only one write operation is executed, and when we add a read lock, it is not restricted to multiple read threads to access. that is, the get and put are mutually exclusive,and theput is mutually exclusive to any thread, but get and Get threads are not mutually exclusive. In fact, the purpose of the read-write lock is the same lock can be locked with the write lock is mutually exclusive, read the lock can also be shared.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JAVA concurrent Programming-read-write lock simulation cache system (11)

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.