首页 > 应用开发 > Java > java写一个支持缓存过期时间的哈希表。
实现一个支持缓存过期时间的哈希表是一个常见的需求,特别是在需要缓存机制的应用中。你可以使用一个
HashMap 来存储键值对,并结合一个优先级队列或类似的数据结构来管理过期时间。下面是一个简单的实现示例,使用
HashMap 和
ConcurrentHashMap(线程安全版本)结合
PriorityQueue 来管理带有过期时间的缓存。
javaCopy Codeimport java.util.HashMap;import java.util.Map;import java.util.PriorityQueue;import java.util.concurrent.ConcurrentHashMap;class CacheItem<K, V> implements Comparable<CacheItem<K, V>> {
K key;
V value; long expiryTime; // 过期时间的时间戳
public CacheItem(K key, V value, long expiryTime) { this.key = key; this.value = value; this.expiryTime = expiryTime;
} @Override
public int compareTo(CacheItem<K, V> other) { return Long.compare(this.expiryTime, other.expiryTime);
}
}public class ExpiringCache<K, V> { private final Map<K, CacheItem<K, V>> cacheMap; private final PriorityQueue<CacheItem<K, V>> expiryQueue; public ExpiringCache() { this.cacheMap = new ConcurrentHashMap<>(); this.expiryQueue = new PriorityQueue<>();
} public void put(K key, V value, long ttlMillis) { long expiryTime = System.currentTimeMillis() + ttlMillis;
CacheItem<K, V> newItem = new CacheItem<>(key, value, expiryTime); // 如果键已经存在,先从队列中移除旧项
if (cacheMap.containsKey(key)) {
CacheItem<K, V> oldItem = cacheMap.get(key);
expiryQueue.remove(oldItem);
}
cacheMap.put(key, newItem);
expiryQueue.add(newItem); // 清理过期的项(可选,可以在每次操作时清理,也可以单独线程定期清理)
cleanup();
} public V get(K key) {
CacheItem<K, V> item = cacheMap.get(key); if (item != null && System.currentTimeMillis() < item.expiryTime) { return item.value;
} // 如果过期或不存在,移除该项(可选)
cacheMap.remove(key); return null;
} public void remove(K key) {
CacheItem<K, V> item = cacheMap.remove(key); if (item != null) {
expiryQueue.remove(item);
}
} private void cleanup() { long now = System.currentTimeMillis(); while (!expiryQueue.isEmpty() && expiryQueue.peek().expiryTime <= now) {
CacheItem<K, V> expiredItem = expiryQueue.poll();
cacheMap.remove(expiredItem.key);
}
} public static void main(String[] args) throws InterruptedException {
ExpiringCache<String, String> cache = new ExpiringCache<>();
cache.put("key1", "value1", 1000); // 1秒过期
System.out.println("key1: " + cache.get("key1")); // 输出: value1
Thread.sleep(1500); // 等待1.5秒
System.out.println("key1 after expiry: " + cache.get("key1")); // 输出: null
}
}
CacheItem 类:
Comparable 接口,以便在
PriorityQueue 中按过期时间排序。 ExpiringCache 类:
ConcurrentHashMap 存储缓存项,确保线程安全。PriorityQueue 按过期时间排序缓存项,以便快速找到过期的项。put 方法:插入新项,并更新
PriorityQueue。如果键已存在,先移除旧项。get 方法:获取缓存项的值,如果项已过期,返回
null 并移除该项。remove 方法:从缓存中移除指定项。cleanup 方法:移除所有已过期的项。这个方法可以在每次操作时调用,或者由一个单独的线程定期调用以提高性能。ConcurrentHashMap 确保多线程环境下的安全性。PriorityQueue 的操作(如插入和删除)是对数时间复杂度,适合中小规模的缓存。对于大规模缓存,可以考虑使用更高效的数据结构或外部库。这个实现提供了一个基本的缓存过期机制,适用于需要简单缓存功能的场景。
http://travel.zgjzs.org
http://hotel.zgjzs.org
http://food.zgjzs.org
http://tech.zgjzs.org
http://health.zgjzs.org
http://edu.zgjzs.org
http://music.zgjzs.org
http://sports.zgjzs.org
http://fashion.zgjzs.org
http://auto.zgjzs.org
http://finance.zgjzs.org
http://law.zgjzs.org
http://art.zgjzs.org
http://book.zgjzs.org
http://movie.zgjzs.org
http://game.zgjzs.org
http://job.zgjzs.org
http://house.zgjzs.org
http://kids.zgjzs.org
http://pet.zgjzs.org
http://beauty.zgjzs.org
http://garden.zgjzs.org
http://science.zgjzs.org
http://history.zgjzs.org
http://culture.zgjzs.org
http://city.zgjzs.org
http://weather.zgjzs.org
http://map.zgjzs.org
http://data.zgjzs.org
http://energy.zgjzs.org
http://eco.zgjzs.org
http://farm.zgjzs.org
http://market.zgjzs.org
http://trade.zgjzs.org
http://service.zgjzs.org
http://club.zgjzs.org
http://event.zgjzs.org
http://festival.zgjzs.org
http://expo.zgjzs.org
http://museum.zgjzs.org
http://library.zgjzs.org
http://school.zgjzs.org
http://hospital.zgjzs.org
http://bank.zgjzs.org
http://insurance.zgjzs.org
http://stock.zgjzs.org
http://invest.zgjzs.org
http://tour.zgjzs.org
http://electronics.shangpin.org
http://clothing.shangpin.org
http://furniture.shangpin.org
http://jewelry.shangpin.org
http://cosmetic.shangpin.org
http://digital.shangpin.org
http://appliance.shangpin.org
http://outdoor.shangpin.org
http://sporting.shangpin.org
http://luxury.shangpin.org
http://grocery.shangpin.org
http://office.shangpin.org
http://tool.shangpin.org
http://craft.shangpin.org
http://antique.shangpin.org
http://collectible.shangpin.org
http://handmade.shangpin.org
http://organic.shangpin.org
http://baby.shangpin.org
http://watch.shangpin.org
http://bag.shangpin.org
http://shoe.shangpin.org
http://glass.shangpin.org
http://ceramic.shangpin.org
http://textile.shangpin.org
http://metal.shangpin.org
http://wood.shangpin.org
http://stone.shangpin.org
http://plastic.shangpin.org
http://paper.shangpin.org
http://ink.shangpin.org
http://paint.shangpin.org
http://lighting.shangpin.org
http://kitchen.shangpin.org
http://bath.shangpin.org
http://bed.shangpin.org
http://sofa.shangpin.org
http://carpet.shangpin.org
http://curtain.shangpin.org
http://lamp.shangpin.org
http://mirror.shangpin.org
http://clock.shangpin.org
http://vase.shangpin.org
http://frame.shangpin.org
http://toy.shangpin.org
http://instrument.shangpin.org
http://plant.shangpin.org
http://gift.shangpin.org
http://business.snjrw.org
http://media.snjrw.org
http://design.snjrw.org
http://photo.snjrw.org
http://video.snjrw.org
http://studio.snjrw.org
http://network.snjrw.org
http://cloud.snjrw.org
http://career.snjrw.org
http://learning.snjrw.org
http://research.snjrw.org
http://innovation.snjrw.org
http://project.snjrw.org
http://solution.snjrw.org
http://global.snjrw.org
http://local.snjrw.org
http://china.snjrw.org
http://asia.snjrw.org
http://europe.snjrw.org
http://america.snjrw.org
http://africa.snjrw.org
http://ocean.snjrw.org
http://space.snjrw.org
http://earth.snjrw.org
http://nature.snjrw.org
http://green.snjrw.org
http://future.snjrw.org
http://ai.snjrw.org
http://robot.snjrw.org
http://vr.snjrw.org
http://ar.snjrw.org
http://iot.snjrw.org
http://blockchain.snjrw.org
http://crypto.snjrw.org
http://nft.snjrw.org
http://metaverse.snjrw.org
http://smart.snjrw.org
http://safe.snjrw.org
http://privacy.snjrw.org
http://security.snjrw.org
http://trust.snjrw.org
http://quality.snjrw.org
http://certified.snjrw.org
http://premium.snjrw.org
http://elite.snjrw.org
http://vip.snjrw.org
http://prime.snjrw.org
http://gold.snjrw.org
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70040412/viewspace-3084187/ ,如需转载,请注明出处,否则将追究法律责任。