Java DelayQueue包装类
2024-10-21 04:02:05
public class DelayQueueWrapper<T> {
private TimeUnit timeUnit;
private final Long capacity;
private long currentSize;
private DelayQueue<DelayQueueTarget<T>> delayQueue;
public DelayQueueWrapper(long capacity, TimeUnit timeUnit) {
this.delayQueue = new DelayQueue<>();
this.capacity = capacity;
this.currentSize = 0;
}
/**
* offer element
* @param t
* @param delay
* @return
*/
public synchronized boolean offer(T t, long delay) {
if (this.currentSize > capacity) {
return false;
}
this.delayQueue.add(new DelayQueueTarget<T>(t, timeUnit.toMillis(delay)));
this.currentSize++;
return true;
}
/**
* peek element
* @return
*/
public synchronized T peek(){
if (this.currentSize < 0) {
return null;
}
T t = Optional.ofNullable(this.delayQueue.peek())
.map(DelayQueueTarget::getData)
.orElse(null);
this.currentSize--;
return t;
}
public static class DelayQueueTarget<T> implements Delayed{
private T data;
private long startTime;
public DelayQueueTarget(T data, long delayInMilliseconds) {
this.data = data;
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return Ints.saturatedCast(
this.startTime - ((DelayQueueTarget<?>) o).startTime);
}
public T getData() {
return data;
}
}
}
最新文章
- HDU 5008 Boring String Problem(后缀数组+二分)
- Matrix QR Decomposition using OpenCV
- Redis总结笔记(一):安装和常用命令
- php-fpm参数调优
- shutdown -s -t
- C#使用HttpHelper万能框架,重启路由器
- Oracle函数题
- 创建以及加载模块【nodejs第四篇】
- HTML基础知识(未完待续)
- ARP攻击之Kali Linux局域网断网攻击
- RDIFramework.NET V3.3 Web版新增日程管理功能模块
- linux防火墙,高级策略策略实例详解(实例一)
- overridePendingTransition
- topcoder srm 689 div1 -3
- def chi(*food,**kw):
- helloworld讲解cocos2d-x的编程思路与要点
- Druid.io系列(二):基本概念与架构
- RNN、LSTM、Char-RNN 学习系列(一)
- 在Mac上激活Adobe产品
- 【Sprint3冲刺之前】日历表的事件处理和管理(刘铸辉)
热门文章
- TypeError: unsupported operand type(s) for |=: &#39;dict&#39; and &#39;dict&#39;
- CF1764G1 题解
- 关于使用C++调用WCF的方法
- Java--判空方法
- windows 10中Microsoft Edge Beta登录账户提示:以管理员身份运行 Microsoft Edge 时不支持登录。请以非管理员身份重新启动 Microsoft Edge,然后重新尝试登录。的解决方案
- v-if和v-show最重要一点
- Spring的AOP源码解析(二)
- python中周日历与时间的相互转换
- 批量添加esxi主机到Vcenter
- openframeworks 设置不显示控制台窗口