注:如果要实现类似spring cache的这种注解形式的,可以配合自定义注解及aop使用。
主要实现
1:单例的类,map,读写锁
/**
* Created by zs.xu on 2020/8/19.
*/
public class MyCache {
public static MyCache myCache;
private MyCache(){};
public static MyCache getInstance(){
if (myCache==null){
synchronized (MyCache.class){
if (null==myCache){
myCache = new MyCache();
}
}
}
return myCache;
}
private volatile Map<String,Object> cacheMap = new HashMap<>();
private ReentrantReadWriteLock lock= new ReentrantReadWriteLock();
public void put(String key,Object value){
if ((null==key||"".equals(key))||null==value){
//key,value 不允许为空
return;
}
//写入时加写锁
lock.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"\t 正在写入"+ key);
TimeUnit.MILLISECONDS.sleep(300);
cacheMap.put(key, value);
System.out.println(Thread.currentThread().getName()+"\t 写入完成!");
}catch (Exception e){
}finally {
lock.writeLock().unlock();
}
}
public Object get(String key){
if (null==key||"".equals(key)){
return null;
}
lock.readLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"\t 正在读入"+ key);
try{
TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e){e.printStackTrace();}
Object result= cacheMap.get(key);
System.out.println(Thread.currentThread().getName()+"\t 读入完成"+result);
}catch (Exception e){
}finally {
lock.readLock().unlock();
}
return null;
}
public void cleanMap(){
cacheMap.clear();
}
}