Java InMemoryCache
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105package pay.infrastructure.helper; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.map.LRUMap; import java.util.ArrayList; /** * Created by wangxiaoming on 2016/3/14. */ public class InMemoryCache<TK, TV> { protected class CrunchifyCacheObject { public long lastAccessed; public TV value; protected CrunchifyCacheObject(TV value) { lastAccessed = System.currentTimeMillis(); this.value = value; } } private long timeToLive; private LRUMap crunchifyCacheMap; public InMemoryCache(long crunchifyTimeToLive, final long crunchifyTimerInterval, int maxItems) { crunchifyCacheMap = new LRUMap(maxItems); this.timeToLive = crunchifyTimeToLive * 1000; if (timeToLive > 0 && crunchifyTimerInterval > 0) { Thread t = new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(crunchifyTimerInterval * 1000); } catch (InterruptedException ex) { } cleanup(); } } }); t.setDaemon(true); t.start(); } } public void put(TK key, TV value) { synchronized (crunchifyCacheMap) { crunchifyCacheMap.put(key, new CrunchifyCacheObject(value)); } } @SuppressWarnings("unchecked") public TV get(TK key) { synchronized (crunchifyCacheMap) { CrunchifyCacheObject c = (CrunchifyCacheObject) crunchifyCacheMap.get(key); if (c == null) { return null; } else { c.lastAccessed = System.currentTimeMillis(); return c.value; } } } public void remove(TK key) { synchronized (crunchifyCacheMap) { crunchifyCacheMap.remove(key); } } public int size() { synchronized (crunchifyCacheMap) { return crunchifyCacheMap.size(); } } @SuppressWarnings("unchecked") public void cleanup() { long now = System.currentTimeMillis(); ArrayList<TK> deleteKey = null; synchronized (crunchifyCacheMap) { MapIterator itr = crunchifyCacheMap.mapIterator(); deleteKey = new ArrayList<>((crunchifyCacheMap.size() / 2) + 1); while (itr.hasNext()) { TK key = (TK) itr.next(); CrunchifyCacheObject c = (CrunchifyCacheObject) itr.getValue(); if (c != null && (now > (timeToLive + c.lastAccessed))) { deleteKey.add(key); } } } for (TK key : deleteKey) { synchronized (crunchifyCacheMap) { crunchifyCacheMap.remove(key); } Thread.yield(); } } }
posted on 2016-09-07 12:02 RockyLOMO 阅读(...) 评论(...) 编辑 收藏
最后
以上就是淡然丝袜最近收集整理的关于Java InMemoryCache的全部内容,更多相关Java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复