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 agree to do multiple read operations at the same time, but only agree to a write operation, such as a file, only the content of the same time to allow multiple threads to read, do not have to do an exclusive lock, the exclusive lock is only required at the time of writing, To ensure that other threads do not see a file with incomplete data. The use of read-write locks is required.


/** * 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;//shared data. Only one thread can write that data, but can have multiple threads reading that 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

It is inevitable to see here that people will ask. Since you can read more people. So why do you need to read the lock?

A: Of course, to lock, or to read when writing, may not be - (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) {}//defines the read-write lock private Readwritelock RWL = new Reentrantreadwritelock ();//Read data. Use read lock public  object GetData (String key) {//join 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{//if three threads are going to get a write lock at the same time, We know that only the first thread can get                    //Then the other two threads just have to wait, and if the first thread runs out of the process, just two threads can get a write lock,                    //And then the data can be changed (assigned value). So add the inference!if (value== NULL) {//Why do you infer it? 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 running, and when we add a read lock, it does not restrict access to multiple read threads. that is, the get and put are mutually exclusive. put and whatever thread are mutually exclusive. However , get and get threads are not mutually exclusive. In fact, the purpose of reading and writing locks is that the same lock read lock can be mutually exclusive to the write lock, and the read lock can also be shared.




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.