博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自定义缓存类
阅读量:7043 次
发布时间:2019-06-28

本文共 1934 字,大约阅读时间需要 6 分钟。

hot3.png

public class CacheMap
extends AbstractMap
{ //默认保存时间 private static final long DEFAULT_TIMEOUT = 1000*60*10; private static CacheMap
defaultInstance; //缓存时间 private long cacheTimeout; private Map
map = new HashMap
(); public CacheMap(long timeout) { this.cacheTimeout = timeout; new ClearThread().start(); } public static synchronized final CacheMap
getDefault() { if (defaultInstance == null) { defaultInstance = new CacheMap
(DEFAULT_TIMEOUT); } return defaultInstance; } //缓存实体 private class CacheEntry implements Entry
{ long time; V value; K key; CacheEntry(K key, V value) { super(); this.value = value; this.key = key; this.time = System.currentTimeMillis(); } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { return this.value = value; } } //清理缓存线程 private class ClearThread extends Thread { ClearThread() { setName("clear cache thread"); } public void run() { while (true) { try { long now = System.currentTimeMillis(); Object[] keys = map.keySet().toArray(); for (Object key : keys) { CacheEntry entry = map.get(key); if (now - entry.time >= cacheTimeout) { synchronized (map) { map.remove(key); } } } Thread.sleep(cacheTimeout); } catch (Exception e) { e.printStackTrace(); } } } } @Override public Set
> entrySet() { Set
> entrySet = new HashSet
>(); Set
> wrapEntrySet = map.entrySet(); for (Entry
entry : wrapEntrySet) { entrySet.add(entry.getValue()); } return entrySet; } @Override public V get(Object key) { CacheEntry entry = map.get(key); return entry == null ? null : entry.value; } @Override public V put(K key, V value) { CacheEntry entry = new CacheEntry(key, value); synchronized (map) { map.put(key, entry); } return value; }}

转载于:https://my.oschina.net/zhengweishan/blog/3043774

你可能感兴趣的文章
ReentrantReadWriteLock类的使用
查看>>
centos下安装五笔
查看>>
spring eureka-server配置
查看>>
ul动态生成li(JavaScript写)
查看>>
android自定义TabWidget
查看>>
SPRINGBOOT 使用技巧总结
查看>>
使用@ResponseBody返回Json格式数据时的配置
查看>>
解决ADB版本不兼容的问题
查看>>
42.Tornado WEB服务器入门
查看>>
递归、闭包、私有变量、特权方法、单例、模块模式(module pattern)
查看>>
java Annotations(批注)
查看>>
Linux利用OneinStack搭建环境
查看>>
写一个简单的运行Django项目的脚本
查看>>
Django
查看>>
解决 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YE
查看>>
iOS开发如何实现消息推送机制
查看>>
Android xml application属性详解
查看>>
Android Push Notification实现信息推送使用
查看>>
elk6.4(rpm)安装及kibana汉化
查看>>
发表图片, 弹出界面, 类似QQ发说说时候添加照片的界面(不太会说,见谅)
查看>>