/**
* 简易定时缓存工具
* @Author: yjw 2023-05-18
* @return:
*/
public class CacheUtill {
public static ConcurrentMap<String, SoftReference<Object>> CacheMap = new ConcurrentHashMap<>();
/**
*
* @Author: yjw 2023-05-18
* @param key 缓存key值
* @param value 缓存对象
* @param time 缓存时间单位秒
* @return:
*/
public static void timerCache(String key, Object value, int time){
SoftReference<Object> sf = new SoftReference<Object>(value);
CacheMap.put(key, sf);
Timer timer = new Timer();
timer.schedule(new DeleteTask(key, timer), time * 1000);
}
/**
* 定义一个删除任务
*/
private static class DeleteTask extends TimerTask {
private String key;
private Timer timer;
public DeleteTask(String key, Timer timer) {
this.key = key;
this.timer = timer;
}
@Override
public void run() {
CacheMap.remove(key);
timer.cancel();
if (null != timer) {
timer = null;
}
}
}
}
测试代码
public static void main(String[] args) {
String key = "key";
String value = "value";
CacheUtill.timerCache(key, value, 30);
System.out.println("缓存内容》" + CacheUtill.CacheMap.get(key).get().toString());
try {
//延时5秒
Thread.currentThread().sleep(5000);
System.out.println("5秒后...");
if (CacheUtill.CacheMap.containsKey(key)) {
System.out.println("缓存内容》" +
CacheUtill.CacheMap.get(key).get() == null ? "内容已删除" : CacheUtill.CacheMap.get(key).get().toString());
}
//延时15秒
Thread.currentThread().sleep(10000);
System.out.println("15秒后...");
if (CacheUtill.CacheMap.containsKey(key)) {
System.out.println("缓存内容》" +
CacheUtill.CacheMap.get(key).get() == null ? "内容已删除" : CacheUtill.CacheMap.get(key).get().toString());
}
//延时35秒
Thread.currentThread().sleep(20000);
System.out.println("35秒后...");
if (!CacheUtill.CacheMap.containsKey(key)) {
System.out.println("缓存内容》" +
CacheUtill.CacheMap.get(key).get() == null ? "内容已删除" : CacheUtill.CacheMap.get(key).get().toString());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}