Learn multi-threaded 2---caching simulations

Source: Internet
Author: User

Caching simulations in single-threaded scenarios

Package Com.test;import Java.util.hashmap;import Java.util.map;public class Cachdemo {    private map<string, object> cache = new hashmap<string,object> ();    Public Object GetData (String key) {Object value = Cache.get (key); if (value = = null) {value = "AAAA";//go to the database to check}return Value;
   }}

Using read-write lock to simulate cache in multithreaded situations

Read lock, plus read only, support multithreading concurrency

Write locks, plus you can modify variables, and the threads are mutually exclusive

Note: The second detection of Value==null has two purposes

Detects blocked threads that wake up after writelock to continue execution

In the read lock release, the write lock plus the instant it is possible for the thread to pay value

Package Com.test;import Java.util.hashmap;import Java.util.map;import java.util.concurrent.locks.ReadWriteLock; Import Java.util.concurrent.locks.reentrantreadwritelock;public class Cachedemo {private map<string, Object> cache = new hashmap<string, object> ();p ublic static void Main (string[] args) {//TODO auto-generated method Stub}pri vate Readwritelock rwl = new Reentrantreadwritelock ();p ublic  Object getData (String key) {Rwl.readlock (). Lock (); O Bject value = Null;try{value = Cache.get (key), if (value = = null) {Rwl.readlock (). Unlock (); Rwl.writelock (). Lock (); try{// Detects a blockage after Writelock wakes up to continue executing the thread        //In the read lock release, the write lock plus the instant it is possible to pay value if (value==null) {value = "aaaa") ;}} Finally{rwl.writelock (). Unlock ();} Rwl.readlock (). Lock ();}} Finally{rwl.readlock (). Unlock ();} return value;}}

  

Learn multi-threaded 2---caching simulations

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.