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