首页 > 代码库 > Java InMemoryCache
Java InMemoryCache
package 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 = http://www.mamicode.com/value;"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(); } }}
Java InMemoryCache
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。