Package com. Threadlearn.test;
Import java.util.*;
Import Java.util.concurrent.locks.ReadWriteLock;
Import Java.util.concurrent.locks.ReentrantReadWriteLock;
Interview questions, design a caching system; Use pseudocode to implement public
class Cachedemo {
//Storage object Container
private map<string,object> Map = new Hashmap<string,object> ();
Read and write lock
private Readwritelock RWL = new Reentrantreadwritelock ();
Public Object GetObject (String key) {
Object obj = null;
Rwl.readlock (). Lock ();
try{
if (Map.get (key) ==null) {
rwl.readlock (). Unlock ();
Rwl.writelock (). Lock ();
try{
obj = Readfromdb ();
} finally{
rwl.writelock (). Unlock ();
}
Rwl.readlock (). Lock ();
} else{
obj = map.get (key);
}
catch (Exception ex) {
ex.printstacktrace ();
} finally{
rwl.readlock (). Unlock ();
}
return obj;
}
The public Object Readfromdb () {
//reads data from the database, the code is slightly return
null;
}
}