Read/write locks: ReadWriteLock and cache instances; readwritelock instances

Source: Internet
Author: User

Read/write locks: ReadWriteLock and cache instances; readwritelock instances
Read/write locks: Multiple read locks are not mutually exclusive. Read locks are mutually exclusive with some locks. Write locks and write locks are mutually exclusive. That is, writing is not allowed during reading, and reading is not allowed during writing.The synchronized keyword and the Lock constructed by a common Lock may cause mutual exclusion between read and read. Therefore, the read/write Lock can improve the performance. Example 1: three threads simultaneously read and write a shared data. ImportJava. util. Random;ImportJava. util. concurrent. locks. ReadWriteLock;ImportJava. util. concurrent. locks. ReentrantReadWriteLock;Public ClassReadWriteLockTest {Public Static VoidMain (String [] args ){FinalQueue queue =NewQueue ();For(IntI = 0; I <3; I ++ ){NewThread (){Public VoidRun (){While(True) {Queue. get () ;}}. start ();NewThread (){Public VoidRun (){While(True) {Queue. put (NewRandom (). nextInt (10000) ;}}. start ();}}}ClassQueue {PrivateObject data =Null; // Share data. Only one thread can write the data, but multiple threads can read the data at the same time. ReadWriteLock rwl =NewReentrantReadWriteLock ();Public VoidGet () {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 () + "have read data:" + data );}Catch(InterruptedException e) {e. printStackTrace ();}Finally{Rwl. readLock (). unlock ();}}Public VoidPut (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 ();}}}Example 2: cache instance ImportJava. util. HashMap;ImportJava. util. Map;ImportJava. util. concurrent. locks. ReadWriteLock;ImportJava. util. concurrent. locks. ReentrantReadWriteLock;Public ClassCacheDemo {Private StaticMap <String, Object>Cache=NewHashMap <String, Object> ();PrivateReadWriteLock rwl =NewReentrantReadWriteLock ();PublicObject getData (String key) {// when the thread starts reading, the read lock rwl. readLock (). lock (); Object value =Null;Try{Value =Cache. Get (key); // determines whether a value existsIf(Value =Null) {// Before starting writing, release the read lock first. Otherwise, the write lock cannot get rwl. readLock (). unlock (); // get the write lock and start to write data rwl. writeLock (). lock ();Try{// Judge whether the value is null again, because if both write threads are blocked here, // load data when the value of a thread is null after it is awakened, when another thread is also awakened, if it is not judged, it will execute two writes.If(Value =Null) {Value = ""; // query databaseCache. Put (key, value );}}Finally{Rwl. writeLock (). unlock (); // release the write lock} rwl. readLock (). lock (); // downgrade to read lock after writing }}Finally{Rwl. readLock (). unlock (); // release the read lock}ReturnValue ;}}

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.