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;
}
} }

最新文章

  1. HDU 5008 Boring String Problem(后缀数组+二分)
  2. Matrix QR Decomposition using OpenCV
  3. Redis总结笔记(一):安装和常用命令
  4. php-fpm参数调优
  5. shutdown -s -t
  6. C#使用HttpHelper万能框架,重启路由器
  7. Oracle函数题
  8. 创建以及加载模块【nodejs第四篇】
  9. HTML基础知识(未完待续)
  10. ARP攻击之Kali Linux局域网断网攻击
  11. RDIFramework.NET V3.3 Web版新增日程管理功能模块
  12. linux防火墙,高级策略策略实例详解(实例一)
  13. overridePendingTransition
  14. topcoder srm 689 div1 -3
  15. def chi(*food,**kw):
  16. helloworld讲解cocos2d-x的编程思路与要点
  17. Druid.io系列(二):基本概念与架构
  18. RNN、LSTM、Char-RNN 学习系列(一)
  19. 在Mac上激活Adobe产品
  20. 【Sprint3冲刺之前】日历表的事件处理和管理(刘铸辉)

热门文章

  1. TypeError: unsupported operand type(s) for |=: &#39;dict&#39; and &#39;dict&#39;
  2. CF1764G1 题解
  3. 关于使用C++调用WCF的方法
  4. Java--判空方法
  5. windows 10中Microsoft Edge Beta登录账户提示:以管理员身份运行 Microsoft Edge 时不支持登录。请以非管理员身份重新启动 Microsoft Edge,然后重新尝试登录。的解决方案
  6. v-if和v-show最重要一点
  7. Spring的AOP源码解析(二)
  8. python中周日历与时间的相互转换
  9. 批量添加esxi主机到Vcenter
  10. openframeworks 设置不显示控制台窗口