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.mzph.cn/news/902668.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

国芯思辰|可编程线性霍尔传感器AH820替换HAL825用于汽车涡轮增压

涡轮增压技术是提高发动机的进气能力的技术&#xff0c;霍尔传感器可以达到监测涡轮转速的作用。在涡轮增压器的轴上安装一个永磁体&#xff0c;当涡轮旋转时&#xff0c;永磁体也随之转动&#xff0c;产生周期性变化的磁场。霍尔传感器靠近永磁体安装&#xff0c;能够检测到磁…

(转)正则化等最优化方法介绍

参考&#xff1a; http://blog.csdn.net/pipisorry/article/details/52108040 附带 损失函数&#xff1b;经验风险&#xff1b;正则化&#xff1b;结构风险 损失函数&#xff08;loss function&#xff09;是用来估量你模型的预测值f(x)与真实值Y的不一致程度&#xff0c;它是…

多维时序 | LightGBM多变量时序预测(Matlab完整源码和数据,适合基础小白研究)

多维时序 | LightGBM多变量时序预测&#xff08;Matlab完整源码和数据&#xff0c;适合基础小白研究&#xff09; 目录 多维时序 | LightGBM多变量时序预测&#xff08;Matlab完整源码和数据&#xff0c;适合基础小白研究&#xff09;效果一览基本介绍程序设计参考资料 效果一览…

【解决】Android Gradle Sync 报错 Could not read workspace metadata

异常信息 Caused by: java.io.UncheckedIOException:Could not read workspace metadata from C:\Users\xxx\.gradle\caches\transforms-4\69955912123c68eecd096b71c66ee211\metadata.bin 异常原因 看字面意思是不能读取metadata文件&#xff0c;原因可能是因为缓存目录异常…

Java面试实战:电商场景下的Spring Cloud微服务架构与缓存技术剖析

第一轮提问 面试官: 谢飞机&#xff0c;我们先从基础问题开始。请问你知道Spring Boot和Spring Cloud的区别吗&#xff1f; 谢飞机: 当然知道&#xff01;Spring Boot主要用于快速构建独立运行的Spring应用&#xff0c;而Spring Cloud则是在Spring Boot的基础上实现分布式系统…

Express 路由使用、请求报文参数获取、路由参数提取

Express 路由使用、请求报文参数获取、路由参数提取 &#x1f6e3;️ 一、Express 路由基本用法 const express require(express); const app express();// 基本 GET 路由 app.get(/, (req, res) > {res.send(Hello GET!); });// POST 路由 app.post(/submit, (req, res)…

【前端】手写代码输出题易错点汇总

两天更新完。 const promise new Promise((resolve, reject) > {console.log(1);console.log(2); }); promise.then(() > {console.log(3); }); console.log(4); //1 //2 //4promise.then 是微任务&#xff0c;它会在所有的宏任务执行完之后才会执行&#xff0c;同时需…

基于深度学习和单目测距的前车防撞及车道偏离预警系统

随着人工智能与计算机视觉技术的飞速发展,高级驾驶辅助系统(ADAS)已成为现代汽车智能化的关键标志。它不仅能有效提升行车安全,还能为自动驾驶时代的全面到来奠定坚实基础。本文深入剖析一套功能完备、基于深度学习模型的 ADAS 系统的架构与核心实现,带您领略智能驾驶背后…

JWT(JSON Web Token)用户认证

1、颁发token <!--JWT依赖--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency><dependency><groupId>javax.xml.bind</groupId>…

【质量管理】现代TRIZ(萃智)理论概述

一、什么是TRIZ理论 TRIZ理论,即发明问题解决理论(Teoriya Resheniya Izobreatatelskikh Zadatch),是由前苏联发明家根里奇阿奇舒勒(Genrich S. Altshuller)于1946年创立的。它是一门基于知识的、面向人的发明问题解决系统化方法学。TRIZ理论通过研究大量的专利,总结出技…

大模型学习笔记 day01 提示工程入门1.One-shot Few-shot提示学习法

如何应⽤和激发⼤语⾔模型的各⽅⾯能⼒ 提示⼯程 Prompt engineering 通过输⼊更加合理的提示&#xff0c;引导模型进⾏更有效的结果输出&#xff0c;本质上是⼀种引导和激发模型能⼒的⽅法更加轻量级的引导⽅法&#xff0c;尝试和实施的⻔槛更低&#xff1b;问题是受限于模型…

FPGA初级项目10——基于SPI的DAC芯片进行数模转换

FPGA初级项目10——基于SPI的DAC芯片进行数模转换 DAC芯片介绍 DAC 芯片&#xff08;数字模拟转换器&#xff09;是一种将数字信号转换为连续模拟信号&#xff08;如电压或电流&#xff09;的集成电路&#xff0c;广泛应用于电子系统中&#xff0c;连接数字世界与模拟世界。 …

如何在 Windows上安装 Python 3.6.5?

Windows 系统安装步骤 下载安装包 安装包下载链接&#xff1a;https://pan.quark.cn/s/9294ca0fd46a 运行安装程序 双击下载的 .exe 文件&#xff08;如 python-3.6.5.exe&#xff09;。 勾选 Add Python 3.6 to PATH&#xff08;重要&#xff01;这将自动配置环境变量&…

Cephalon端脑云:神经形态计算+边缘AI·重定义云端算力

前引&#xff1a;当算力不再是“奢侈品” &#xff0c;在人工智能、3D渲染、科学计算等领域&#xff0c;算力一直是横亘在个人与企业面前的“高墙”。高性能服务器价格动辄数十万元&#xff0c;专业设备维护成本高&#xff0c;普通人大多是望而却步。然而&#xff0c;Cephalon算…

【信息系统项目管理师】高分论文:论进度管理和成本管理(智慧城管平台项目)

更多内容请见: 备考信息系统项目管理师-专栏介绍和目录 文章目录 论文1、规划进度管理2、定义活动3、排列活动顺序4、估算活动资源5、估算活动持续时间6、制定进度计划7、控制进度论文 2018年8月,我作为项目经理参与了 XX市智慧城管平台项目的建设,该项目投资500万元人民币…

WebAssembly:开启高性能Web应用新时代

一、引言 随着互联网技术的飞速发展&#xff0c;Web应用的复杂度和性能要求越来越高。传统的Web开发技术&#xff0c;如JavaScript&#xff0c;虽然功能强大&#xff0c;但在处理复杂计算和高性能需求时仍存在一些局限性。WebAssembly&#xff08;简称Wasm&#xff09;作为一种…

操作系统进程管理笔记

1. 进程的基本概念 1.1 进程的定义 进程就是运行中的程序。程序本身是没有生命周期的&#xff0c;它只是存在磁盘上面的一些指令&#xff08;也可能是一些静态数据&#xff09;。是操作系统让这些字节运行起来&#xff0c;让程序发挥作用。 1.2 CPU的时分共享 操作系统通过…

Python中random库的应用

文章目录 一、random 库常用函数二、条件语句 随机数示例1&#xff1a;随机决定程序分支示例2&#xff1a;模拟概率事件 三、循环语句 随机数示例1&#xff1a;循环直到满足随机条件示例2&#xff1a;随机次数循环 四、随机操作数据结构示例1&#xff1a;随机打乱列表顺序示例…

密码学货币混币器详解及python实现

目录 一、前言二、混币器概述2.1 混币器的工作原理2.2 关键特性三、数据生成与预处理四、系统架构与流程五、核心数学公式六、异步任务调度与 GPU 加速七、PyQt6 GUI 设计八、完整代码实现九、自查测试与总结十、展望摘要 本博客聚焦 “密码学货币混币器实现”,以 Python + P…

各种各样的bug合集

一、连不上数据库db 1.可能是密码一大包东西不对&#xff1b; 2.可能是里面某个port和数据库不一样&#xff08;针对于修改了数据库但是连不上的情况&#xff09;&#xff1b; 3.可能是git代码没拉对&#xff0c;再拉一下代码。❤ 二、没有这个包 可能是可以#注释掉。❤ …