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