
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MapCache {
private static volatile MapCache mapCache;
/**
* 默认缓存容量
*/
private static final int INITIAL_CAPACITY = 1024;
/**
* 缓存容器
*/
private final Map<String, Object> cachePool;
/**
* 定时器 用来控制 缓存的超时时间
*/
private final ScheduledExecutorService executorService;
private MapCache(int initialCapacity) {
cachePool = new ConcurrentHashMap<>(initialCapacity);
executorService = new ScheduledThreadPoolExecutor(2);
}
public static MapCache getInstance(){
if (mapCache == null){
synchronized (MapCache.class) {
if (mapCache == null) {
mapCache = new MapCache();
}
}
}
return mapCache;
}
public MapCache() {
this(INITIAL_CAPACITY);
}
/**
* 设置缓存 无过期时间
*
* @param key 键
* @param value 值
*/
public void put(String key, Object value) {
cachePool.put(key, value);
}
/**
* 设置缓存 有过期时间
*
* @param key 键
* @param value 值
* @param timeout 过期时间
*/
public void put(String key, Object value, int timeout) {
cachePool.put(key, value);
executorService.schedule(() -> remove(key), timeout, TimeUnit.SECONDS);
}
/**
* 读取缓存
*
* @param key 键
* @return 返回值
*/
public Object get(String key) {
return cachePool.get(key);
}
/**
* 获取所有key
*
* @return 获取所有key
*/
public Set<String> getKeys() {
return cachePool.keySet();
}
/**
* 获取当前缓存所有内容
* @return
*/
public Map<String ,Object> allCache(){
return cachePool;
}
/**
* 判断缓存是否包含key
* @param key key
* @return 是否包含
*/
public boolean containsKey(String key){
return cachePool.containsKey(key);
}
/**
* 获取当前缓存大小
*
* @return 缓存大小
*/
public int size() {
return cachePool.size();
}
/**
* 根据key删除缓存
*
* @param key key
*/
public void remove(String key) {
cachePool.remove(key);
}
/**
* 清空缓存
*/
public void clean() {
if (size() > 0) {
cachePool.clear();
}
}
}

业务要求较高推荐 ConcurrentHashMap
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通