时间轮java实现 设计一个本地缓存到期后自动清理的示例代码
以下是一个使用时间轮实现本地缓存的示例代码:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LocalCache<K, V> {
private final Map<K, CacheItem<V>> cache;
private final ScheduledExecutorService executorService;
public LocalCache() {
cache = new ConcurrentHashMap<>();
executorService = Executors.newSingleThreadScheduledExecutor();
}
public void put(K key, V value, long duration, TimeUnit unit) {
long expirationTime = System.currentTimeMillis() + unit.toMillis(duration);
CacheItem<V> item = new CacheItem<>(value, expirationTime);
cache.put(key, item);
executorService.schedule(() -> {
cache.remove(key);
}, duration, unit);
}
public V get(K key) {
CacheItem<V> item = cache.get(key);
if (item != null && item.getExpirationTime() > System.currentTimeMillis()) {
return item.getValue();
}
return null;
}
public void clear() {
cache.clear();
}
private static class CacheItem<V> {
private final V value;
private final long expirationTime;
public CacheItem(V value, long expirationTime) {
this.value = value;
this.expirationTime = expirationTime;
}
public V getValue() {
return value;
}
public long getExpirationTime() {
return expirationTime;
}
}
}
使用示例:
public class Main {
public static void main(String[] args) throws InterruptedException {
LocalCache<String, String> cache = new LocalCache<>();
cache.put("key1", "value1", 5, TimeUnit.SECONDS);
cache.put("key2", "value2", 10, TimeUnit.SECONDS);
System.out.println(cache.get("key1")); // Output: value1
System.out.println(cache.get("key2")); // Output: value2
Thread.sleep(6000);
System.out.println(cache.get("key1")); // Output: null
System.out.println(cache.get("key2")); // Output: value2
cache.clear();
}
}
在上面的示例中,LocalCache类使用ConcurrentHashMap来存储缓存项,并使用ScheduledExecutorService来定期清理过期的缓存项。在put方法中,会计算缓存项的过期时间,并在过期时间到达后从缓存中移除该项。get方法会检查缓存项是否过期,如果没有过期则返回对应的值,否则返回null。clear方法可以清空整个缓存
原文地址: http://www.cveoy.top/t/topic/iXue 著作权归作者所有。请勿转载和采集!