All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.gnux.core.utils.cache.TimedCache Maven / Gradle / Ivy

The newest version!
package cn.gnux.core.utils.cache;


import java.util.HashMap;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时缓存
* 此缓存没有容量限制,对象只有在过期后才会被移除 * * @author * * @param 键类型 * @param 值类型 */ public class TimedCache extends AbstractCache { /** 定时器 */ protected Timer pruneTimer; /** * 构造 * * @param timeout 过期时长 */ public TimedCache(long timeout) { this.capacity = 0; this.timeout = timeout; cacheMap = new HashMap>(); } // ---------------------------------------------------------------- prune /** * 清理过期对象 * @return 清理数 */ @Override protected int pruneCache() { int count = 0; Iterator> values = cacheMap.values().iterator(); CacheObj co; while (values.hasNext()) { co = values.next(); if (co.isExpired()) { values.remove(); count++; } } return count; } // ---------------------------------------------------------------- auto prune /** * 定时清理 * @param delay 间隔时长 */ public void schedulePrune(long delay) { if (pruneTimer != null) { pruneTimer.cancel(); } pruneTimer = new Timer(); pruneTimer.schedule(new TimerTask(){ @Override public void run() { prune(); } }, delay, delay); } /** * 取消定时清理 */ public void cancelPruneSchedule() { if (pruneTimer != null) { pruneTimer.cancel(); pruneTimer = null; } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy