Implement a simple caching mechanism based on synchronized or Readwritelock

Source: Internet
Author: User

1  Packagecn.xxx.xxx;2 3 ImportJava.util.HashMap;4 ImportJava.util.Map;5 ImportJava.util.concurrent.locks.ReadWriteLock;6 ImportJava.util.concurrent.locks.ReentrantReadWriteLock;7 8  Public classCachedemo_my {9 Ten      Public Static voidMain (string[] args) { One         //internal class instantiation requires the static keyword in front of the inner class A         FinalCacheclass Cacheclass =NewCacheclass (); -          for(inti = 0; I < 10; i++) {  -             NewThread (NewRunnable () { the   - @Override -                  Public voidrun () { -Object valueobject = Cacheclass.getdata ("1"); +System.out.println (Thread.CurrentThread (). GetName () + ":" +valueobject); -                 } + }). Start (); A         }  at     } -      -  -     Static classCacheclass { -         Privatemap<string, object> cachemap =NewHashmap<string, object>(); -  in         /** - * 1.0 does not consider concurrency issues: two times from the database to * Query data from the database!  + * Query data from the database!  - * Thread-1: null Why is NULL, concurrent, process as shown in Thread-0 the * Thread-2: AAA * * Thread-0: null why is NULL because no value in the first read map returns NULL, and Cachemap.put (Key, "AAA") $ * is not re-assigned to object so it is nullPanax Notoginseng * solution is obtained directly from Cachemap.get (key), do not intermediate object, here I will not change - * Thread-3: AAA the * Thread-4: AAA + * Thread-5: AAA A * Thread-6: AAA the * Thread-7: AAA + * Thread-8: AAA - * Thread-9: AAA $          *  $          * @paramKey -          * @return -          */ the         //Public Object GetData (String key) { -         //Object value = Cachemap.get (key);Wuyi         //if (value = = null) { the         //System.out.println ("Querying data from a database! "); -         //cachemap.put (Key, "AAA"); Wu         // } -         //return value; About         // } $  -         /** - * 2.0 using synchronized Synchronous code block to solve concurrency problem implementation simple directly add synchronized keyword -          *  A * Query data from the database!  + * Thread-4: BBB the * Thread-1: BBB - * Thread-2: BBB $ * Thread-0: BBB the * Thread-3: BBB the * Thread-8: BBB the * Thread-7: BBB the * Thread-6: BBB - * Thread-9: BBB in * Thread-5: BBB the          *  the          * @paramKey About          * @return the          */ the //Public synchronized Object getData (String key) { the //          + //if (Cachemap.get (key) ==null) { - //System.out.println ("Querying data from a database! "); the //cachemap.put (Key, "BBB");Bayi //         } the //return Cachemap.get (key); the //         } -  -         /** the * 3.0 using read/write lock the          *  the query data from the database!  the Thread-1: CCC - Thread-3: CCC the Thread-4: CCC the Thread-2: CCC the Thread-0: CCC94 Thread-5: CCC the Thread-7: CCC the Thread-8: CCC the Thread-9: CCC98 Thread-6: CCC About          */ -         PrivateReadwritelock RWL =NewReentrantreadwritelock ();101          PublicObject getData (String key) {102             //Lock to try Finally, avoid the exception of the code has been locked103 Rwl.readlock (). Lock ();104             Try { the                 if(Cachemap.get (key) = =NULL) { 106                     Try{107                         //the read lock was removed to write the lock and the lock.108 rwl.readlock (). Unlock ();109                         //Lock to try Finally, avoid the exception of the code has been locked the Rwl.writelock (). Lock ();111                         //prevent the first thread from writing the data, followed by the thread to write the                         if(Cachemap.get (key) = =NULL) {113SYSTEM.OUT.PRINTLN ("Querying data from a database! "); theCachemap.put (Key, "CCC"); the                         } the                     }117                     finally{118 rwl.writelock (). Unlock ();119                     }  - Rwl.readlock (). Lock ();121                 }122}finally {123 rwl.readlock (). Unlock ();124             } the 126             returnCachemap.get (key);127         } -     }129}

Implement a simple caching mechanism based on synchronized or Readwritelock

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.