java设置有时效的变量_可以设置过期时间的Java缓存Map

1 import java.util.*;2

3 /**

4 * @Title: ExpiryMap 可以设置过期时间的Map5 * @description ExpiryMap继承至HashMap 重写了所有对外的方法,对每个key值都设置了有效期6 * @Author: xx7 * @Version: 1.08 */

9 public class ExpiryMap extends HashMap{10

11 private static final long serialVersionUID = 1L;12

13 /**

14 * default expiry time 2s15 */

16 private long EXPIRY = 1000 * 2;17

18 private HashMap expiryMap = new HashMap<>();19

20 /**缓存实例对象*/

21 private volatile static ExpiryMapSameUrlMap;22

23 /**

24 * 采用单例模式获取实例25 *@return

26 */

27 public staticExpiryMap getInstance() {28 //第一次判空,提高效率

29 if (null ==SameUrlMap) {30 //保证线程安全

31 synchronized (ExpiryMap.class) {32 //第二次判空,保证单例对象的唯一性,防止第一次有多个线程进入第一个if判断

33 if (null ==SameUrlMap) {34 SameUrlMap = new ExpiryMap<>();35 }36 }37 }38 returnSameUrlMap;39 }40

41 publicExpiryMap(){42 super();43 }44

45 public ExpiryMap(longdefaultExpiryTime){46 this(1 << 4, defaultExpiryTime);47 }48

49 public ExpiryMap(int initialCapacity, longdefaultExpiryTime){50 super(initialCapacity);51 this.EXPIRY =defaultExpiryTime;52 }53

54 @Override55 publicV put(K key, V value) {56 expiryMap.put(key, System.currentTimeMillis() +EXPIRY);57 return super.put(key, value);58 }59

60 @Override61 public booleancontainsKey(Object key) {62 return !checkExpiry(key, true) && super.containsKey(key);63 }64 /**

65 *@paramkey66 *@paramvalue67 *@paramexpiryTime 键值对有效期 毫秒68 *@return

69 */

70 public V put(K key, V value, longexpiryTime) {71 expiryMap.put(key, System.currentTimeMillis() +expiryTime);72 return super.put(key, value);73 }74

75 @Override76 public intsize() {77 returnentrySet().size();78 }79

80 @Override81 public booleanisEmpty() {82 return entrySet().size() == 0;83 }84

85 @Override86 public booleancontainsValue(Object value) {87 if (value == null) {88 returnBoolean.FALSE;89 }90 Set> set = super.entrySet();91 Iterator> iterator =set.iterator();92 while(iterator.hasNext()) {93 java.util.Map.Entry entry =iterator.next();94 if(value.equals(entry.getValue())){95 if(checkExpiry(entry.getKey(), false)) {96 iterator.remove();97 returnBoolean.FALSE;98 }else{99 returnBoolean.TRUE;100 }101 }102 }103 returnBoolean.FALSE;104 }105

106 @Override107 public Collectionvalues() {108

109 Collection values = super.values();110

111 if(values == null || values.size() < 1) {112 returnvalues;113 }114

115 Iterator iterator =values.iterator();116

117 while(iterator.hasNext()) {118 V next =iterator.next();119 if(!containsValue(next)) {120 iterator.remove();121 }122 }123 returnvalues;124 }125

126 @Override127 publicV get(Object key) {128 if (key == null) {129 return null;130 }131 if(checkExpiry(key, true)) {132 return null;133 }134 return super.get(key);135 }136 /**

137 *138 * @Description: 是否过期139 *@paramkey140 *@returnnull:不存在或key为null -1:过期 存在且没过期返回value 因为过期的不是实时删除,所以稍微有点作用141 */

142 publicObject isInvalid(Object key) {143 if (key == null) {144 return null;145 }146 if(!expiryMap.containsKey(key)){147 return null;148 }149 long expiryTime =expiryMap.get(key);150

151 boolean flag = System.currentTimeMillis() >expiryTime;152

153 if(flag){154 super.remove(key);155 expiryMap.remove(key);156 return -1;157 }158 return super.get(key);159 }160

161 @Override162 public void putAll(Map extends K, ? extends V>m) {163 for (Map.Entry extends K, ? extends V>e : m.entrySet()) {164 expiryMap.put(e.getKey(), System.currentTimeMillis() +EXPIRY);165 }166 super.putAll(m);167 }168

169 @Override170 public Set>entrySet() {171 Set> set = super.entrySet();172 Iterator> iterator =set.iterator();173 while(iterator.hasNext()) {174 java.util.Map.Entry entry =iterator.next();175 if(checkExpiry(entry.getKey(), false)) {176 iterator.remove();177 }178 }179

180 returnset;181 }182 /**

183 *184 * @Description: 是否过期185 *@paramexpiryTime true 过期186 *@paramisRemoveSuper true super删除187 *@return

188 */

189 private boolean checkExpiry(Object key, booleanisRemoveSuper){190

191 if(!expiryMap.containsKey(key)){192 returnBoolean.FALSE;193 }194 long expiryTime =expiryMap.get(key);195

196 boolean flag = System.currentTimeMillis() >expiryTime;197

198 if(flag){199 if(isRemoveSuper) {200 super.remove(key);201 }202 expiryMap.remove(key);203 }204 returnflag;205 }206

207 public static void main(String[] args) throwsInterruptedException {208 ExpiryMap map = new ExpiryMap<>();209 map.put("test", "xxx");210 map.put("test2", "ankang", 5000);211 System.out.println("test==" + map.get("test"));212 Thread.sleep(3000);213 System.out.println("test==" + map.get("test"));214 System.out.println("test2==" + map.get("test2"));215 Thread.sleep(3000);216 System.out.println("test2==" + map.get("test2"));217 }218 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Java 中的 ConcurrentHashMap 数据结构和 ScheduledExecutorService 实现带过期时间缓存。具体实现步骤如下: 1. 创建一个 ConcurrentHashMap 对象来存储缓存数据,key 为缓存的键,value 为缓存的值和过期时间。 2. 创建一个 ScheduledExecutorService 组件,用来定期清理过期缓存。 3. 实现一个 put 方法来向缓存中添加数据,该方法会将数据存入 ConcurrentHashMap 中,并且将过期时间也存入 value 中。 4. 实现一个 get 方法来从缓存中获取数据,该方法会先检查数据是否过期,如果过期则删除该数据并返回 null,否则返回缓存数据的值。 5. 实现一个定时任务,定期遍历 ConcurrentHashMap,删除过期缓存数据。 实现代码示例: ```java import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ExpireCache<K, V> { private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>(); private final ConcurrentHashMap<K, Long> expireTime = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); public ExpireCache() { // 定时任务,每隔 1 秒遍历缓存并删除过期数据 executorService.scheduleWithFixedDelay(() -> { long now = System.currentTimeMillis(); cache.forEach((k, v) -> { Long expire = expireTime.get(k); if (expire != null && now > expire) { cache.remove(k); expireTime.remove(k); } }); }, 1, 1, TimeUnit.SECONDS); } public void put(K key, V value, long expireAfter) { cache.put(key, value); expireTime.put(key, System.currentTimeMillis() + expireAfter); } public V get(K key) { V value = cache.get(key); if (value != null) { Long expire = expireTime.get(key); if (expire == null || System.currentTimeMillis() <= expire) { return value; } else { cache.remove(key); expireTime.remove(key); } } return null; } } ``` 使用示例: ```java ExpireCache<String, String> cache = new ExpireCache<>(); cache.put("key1", "value1", 5000); // 缓存 5 秒 cache.put("key2", "value2", 10000); // 缓存 10 秒 // 获取缓存数据 System.out.println(cache.get("key1")); // 输出 value1 System.out.println(cache.get("key2")); // 输出 value2 Thread.sleep(6000); // 等待 6 秒 // 获取缓存数据 System.out.println(cache.get("key1")); // 输出 null System.out.println(cache.get("key2")); // 输出 value2 Thread.sleep(5000); // 等待 5 秒 // 获取缓存数据 System.out.println(cache.get("key2")); // 输出 null ``` 在上述示例中,使用 ExpireCache 类来实现带过期时间缓存缓存数据的过期时间分别为 5 秒和 10 秒。在获取缓存数据时,如果数据已经过期,则返回 null,否则返回缓存数据的值。缓存数据的清理是通过定时任务来实现的,每隔 1 秒遍历缓存并删除过期数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值