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

cn.hutool.cache.impl.TimedCache Maven / Gradle / Ivy

Go to download

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

There is a newer version: 5.8.34
Show newest version
package cn.hutool.cache.impl;

import cn.hutool.cache.GlobalPruneTimer;
import cn.hutool.core.lang.mutable.Mutable;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * 定时缓存
* 此缓存没有容量限制,对象只有在过期后才会被移除 * * @author Looly * * @param 键类型 * @param 值类型 */ public class TimedCache extends StampedCache { private static final long serialVersionUID = 1L; /** 正在执行的定时任务 */ private ScheduledFuture pruneJobFuture; /** * 构造 * * @param timeout 超时(过期)时长,单位毫秒 */ public TimedCache(long timeout) { this(timeout, new HashMap<>()); } /** * 构造 * * @param timeout 过期时长 * @param map 存储缓存对象的map */ public TimedCache(long timeout, Map, CacheObj> map) { this.capacity = 0; this.timeout = timeout; this.cacheMap = map; } // ---------------------------------------------------------------- prune /** * 清理过期对象 * * @return 清理数 */ @Override protected int pruneCache() { int count = 0; final Iterator> values = cacheObjIter(); CacheObj co; while (values.hasNext()) { co = values.next(); if (co.isExpired()) { values.remove(); onRemove(co.key, co.obj); count++; } } return count; } // ---------------------------------------------------------------- auto prune /** * 定时清理 * * @param delay 间隔时长,单位毫秒 */ public void schedulePrune(long delay) { this.pruneJobFuture = GlobalPruneTimer.INSTANCE.schedule(this::prune, delay); } /** * 取消定时清理 */ public void cancelPruneSchedule() { if (null != pruneJobFuture) { pruneJobFuture.cancel(true); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy