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

org.tio.utils.cache.FIFOCache Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package org.tio.utils.cache;

import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * FIFO(first in first out) 先进先出缓存.
 *
 * 

* 元素不停的加入缓存直到缓存满为止,当缓存满时,清理过期缓存对象,清理后依旧满则删除先入的缓存(链表首部对象)
* 优点:简单快速
* 缺点:不灵活,不能保证最常用的对象总是被保留 *

* * @param 键类型 * @param 值类型 * @author Looly */ public class FIFOCache extends StampedCache { private static final long serialVersionUID = 1L; /** * 构造,默认对象不过期 * * @param capacity 容量 */ public FIFOCache(int capacity) { this(capacity, 0); } /** * 构造 * * @param capacity 容量 * @param timeout 过期时长 */ public FIFOCache(int capacity, long timeout) { super(getCacheMap(capacity), capacity, timeout); } private static Map> getCacheMap(int capacity) { return new LinkedHashMap<>(capacity + 1, 1.0f, false); } /** * 先进先出的清理策略
* 先遍历缓存清理过期的缓存对象,如果清理后还是满的,则删除第一个缓存对象 */ @Override protected int pruneCache() { int count = 0; CacheObj first = null; // 清理过期对象并找出链表头部元素(先入元素) final Iterator> values = cacheObjIter(); if (isPruneExpiredActive()) { // 清理过期对象并找出链表头部元素(先入元素) while (values.hasNext()) { CacheObj co = values.next(); if (co.isExpired()) { values.remove(); onRemove(co.key, co.obj); count++; continue; } if (first == null) { first = co; } } } else { first = values.hasNext() ? values.next() : null; } // 清理结束后依旧是满的,则删除第一个被缓存的对象 if (isFull() && null != first) { removeWithoutLock(first.key, false); onRemove(first.key, first.obj); count++; } return count; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy