当前位置: 首页 > backend >正文

java延迟map, 自定义延迟map, 过期清理map,map能力扩展。如何设置map数据过期,改造map适配数据过期

1. 功能:

            map 线程安全,能够对存入的数据设置过期,或者自定义删除

2. aliyun代码看到的一个对象正好符合上述需求

    出处是aliyun sdk core jar包的一个类。感兴趣可以去下载下jar查看

下面是源码:

package com.aliyuncs.policy.cache;import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;public class ThrottlingPool {private static final Map<String, Entity> map = new ConcurrentHashMap();private static final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, (new BasicThreadFactory.Builder()).namingPattern("throttling-pool-%d").daemon(true).build());public ThrottlingPool() {}public static synchronized void put(String key, Object data) {put(key, data, -1);}public static synchronized void put(final String key, Object data, int expire) {remove(key);if (data != null) {if (expire >= 0) {Future future = executor.schedule(new Runnable() {public void run() {synchronized(ThrottlingPool.class) {ThrottlingPool.map.remove(key);}}}, (long)expire, TimeUnit.MILLISECONDS);map.put(key, new Entity(data, expire, future));} else {map.put(key, new Entity(data, expire, (Future)null));}}}public static synchronized Object get(String key) {Entity entity = (Entity)map.get(key);return entity != null ? entity.getValue() : null;}public static synchronized <T> T get(String key, Class<T> clazz) {return (T)clazz.cast(get(key));}public static synchronized int getExpire(String key) {Entity entity = (Entity)map.get(key);return entity != null ? entity.getExpire() : 0;}public static synchronized Object remove(String key) {Entity entity = (Entity)map.remove(key);if (entity == null) {return null;} else {Future future = entity.getFuture();if (future != null) {future.cancel(true);}return entity.getValue();}}public static synchronized int size() {return map.size();}public static synchronized void clear() {for(Entity entity : map.values()) {if (entity != null) {Future future = entity.getFuture();if (future != null) {future.cancel(true);}}}map.clear();}public static synchronized Map<String, Entity> getPool() {return map;}private static class Entity {private Object value;private int expire;private Future future;public Entity(Object value, int expire, Future future) {this.value = value;this.expire = expire;this.future = future;}public Object getValue() {return this.value;}public int getExpire() {return this.expire;}public Future getFuture() {return this.future;}}
}

2. 但是有个问题,如果数据量大,且都设置有过期时间,容易过期不及时!单线程处理不过来

3. 下面代码采用延迟队列一版:

import java.util.concurrent.*;public class ThrottlingPool {private static final ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();private static final DelayQueue<DelayedCacheEntry> delayQueue = new DelayQueue<>();private static final ExecutorService executor = Executors.newSingleThreadExecutor(r -> {Thread t = new Thread(r);t.setDaemon(true);return t;});public static void put(String key, Object data, long expireMs) {long expirationTime = System.currentTimeMillis() + expireMs;delayQueue.removeIf(entry -> entry.getKey().equals(key));map.put(key, data);delayQueue.offer(new DelayedCacheEntry(key, expirationTime));}public static Object get(String key) {return map.get(key);}public static void remove(String key) {map.remove(key);}public static int size() {return map.size();}// 启动一个后台线程处理过期任务static {executor.execute(() -> {while (!Thread.currentThread().isInterrupted()) {try {DelayedCacheEntry entry = delayQueue.take();
//                    synchronized (ThrottlingPool.class) {map.remove(entry.getKey());
//                    }} catch (InterruptedException ex) {ex.printStackTrace();Thread.currentThread().interrupt();break;}}});// 钩子Runtime.getRuntime().addShutdownHook(new Thread(() -> {executor.shutdown();}));
//        Thread cleanupThread = new Thread(() -> {
//            while (true) {
//                try {
//                    DelayedCacheEntry entry = delayQueue.take();
//                    synchronized (ThrottlingPool.class) {
//                        map.remove(entry.getKey());
//                    }
//                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();
//                    break;
//                }
//            }
//        });
//        cleanupThread.setDaemon(true);
//        cleanupThread.start();}private static class DelayedCacheEntry implements Delayed {private final String key;private final long expirationTime;public DelayedCacheEntry(String key, long expirationTime) {this.key = key;this.expirationTime = expirationTime;}@Overridepublic long getDelay(TimeUnit unit) {long diff = expirationTime - System.currentTimeMillis();return unit.convert(diff, TimeUnit.MILLISECONDS);}@Overridepublic int compareTo(Delayed o) {return Long.compare(this.expirationTime, ((DelayedCacheEntry) o).expirationTime);}public String getKey() {return key;}}}

4.本人水平有限,如有问题,欢迎指正

http://www.xdnf.cn/news/1760.html

相关文章:

  • day6-小白学习JAVA---方法_面向对象
  • 了解低功耗蓝牙中的安全密钥
  • 缓存穿透、雪崩、击穿深度解析与解决方案
  • 多线程中的ABA问题详解
  • Java并发编程|CompletableFuture原理与实战:从链式操作到异步编排
  • BGE(BAAI General Embedding)模型详解
  • Nginx 安装与配置全流程指南(2025 最新版)
  • 桌面应用中VUE使用新浏览器窗口打开页面
  • Parasol 将交易卡牌游戏体验带入 Sui
  • Python中的 for 与 迭代器
  • 一种企业信息查询系统设计和实现:xujian.tech/cs
  • 白鲸开源WhaleStudio与崖山数据库管理系统YashanDB完成产品兼容互认证
  • python中socket(套接字)库详细解析
  • 拆解华为Pura X新发现:“仿生”散热与钛合金“骨架”
  • G3学习笔记
  • [C] 第6章 C51函数
  • 音视频之H.265/HEVC量化
  • 项目中数据结构为什么用数组,不用List
  • [Redis] Redis最佳实践
  • 【bmc1】概要,构建image
  • NVIDIA自动驾驶安全与技术读后感
  • 轻松完成视频创作,在线视频编辑器,无需下载软件,功能多样实用!
  • 【国产化之路】VPX-3U :基于D2000 /FT2000的硬件架构到操作系统兼容
  • postgres 导出导入(基于数据库,模式,表)
  • 优先级队列和仿函数的讲解(底层实现)
  • AWS 中国区 CloudFront SSL 证书到期更换实战指南
  • Missashe考研日记-day26
  • c++内存分布
  • 黑马点评--图形化界面连接redis
  • 【刷题】第三弹——二叉树篇(上)