- 浏览: 595983 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
月光杯:
问题解决了吗?
Exceptions in HDFS -
iostreamin:
神,好厉害,这是我找到的唯一可以ac的Java代码,厉害。
[leetcode] word ladder II -
standalone:
One answer I agree with:引用Whene ...
How many string objects are created? -
DiaoCow:
不错!,一开始对这些确实容易犯迷糊
erlang中的冒号 分号 和 句号 -
standalone:
Exception in thread "main& ...
one java interview question
今天不忙,学习一下java.util.concurrent.DelayQueue这个类的使用。参照了
http://www.concretepage.com/java/example_delayqueue_java.php
上的例子,但是这里有个坑。
先看一下整个code吧:
注意getDelay(TimeUnit unit),这个是实现Delayed这个接口时候必须要实现的一个方法,容易遇坑的地方就是
这里应该使用的TimeUnit.MILLISECONDS而不是TimeUnit.NANOSECONDS,但是你会发现不管你用哪一个(或者其他的TimeUnit),这个程序的正确性是ok的,都会delay你所要的时间,例如分别使用这两种TimeUnit的输出:
If using MILLISECONDS:
current time in ms: 1369644922697
current time in ms: 1369644923697, element:e1
current time in ms: 1369644924197, element:e3
current time in ms: 1369644927697, element:e2
If using NANOSECONDS:
current time in ms: 1369645748910
current time in ms: 1369645749910, element:e1
current time in ms: 1369645750410, element:e3
current time in ms: 1369645753910, element:e2
那么会有什么问题呢?
看一下DelayQueue的take()方法会发现,在队列首对象的delay>0的时候,等待的时间单位是nanos(193行),所以如果我刚才getDelay()里面没有将ms转换成ns,那么数值会小很多,line 193 会很快执行,再次循环进行判断,delay仍然大于0,注意,总的等待时间是固定的,现在是每次wait的时间片变小了,所以循环的次数多了,造成一个结果就是cpu占用上升!
如果打印出每次delay的值便可以看到用nanos多做了多少次循环,读者可以自己看一下,呵呵。
遇到这个坑的人我google到有:
http://www.blogjava.net/killme2008/archive/2010/10/22/335897.html
http://www.concretepage.com/java/example_delayqueue_java.php
上的例子,但是这里有个坑。
先看一下整个code吧:
import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayQueueExample { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub DelayQueue<DelayedElement> dq=new DelayQueue<DelayedElement>(); long now = System.currentTimeMillis(); System.out.println("current time in ms: " + now); DelayedElement ob1=new DelayedElement("e1", now + 1000); DelayedElement ob2=new DelayedElement("e2", now + 5000); DelayedElement ob3=new DelayedElement("e3", now + 1500); dq.add(ob1); dq.add(ob2); dq.add(ob3); try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException( e ); } while(dq.size() > 0){ try { DelayedElement e = dq.take(); System.out.println("current time in ms: " + System.currentTimeMillis() + ", element:" + e.name); } catch (InterruptedException e) { throw new RuntimeException( e ); } } } static class DelayedElement implements Delayed { public long time; public String name; public DelayedElement(String name, long time){ this.name = name; this.time = time; } @Override public int compareTo(Delayed o) { // TODO Auto-generated method stub if(this.time < ((DelayedElement)o).time) return -1; else if(this.time > ((DelayedElement)o).time)return 1; else return 0; } @Override public long getDelay(TimeUnit unit) { // TODO Auto-generated method stub long r = unit.convert(time - System.currentTimeMillis(), TimeUnit.NANOSECONDS); //System.out.println("delay:" + r); return r; } } }
注意getDelay(TimeUnit unit),这个是实现Delayed这个接口时候必须要实现的一个方法,容易遇坑的地方就是
long r = unit.convert(time - System.currentTimeMillis(), TimeUnit.NANOSECONDS);
这里应该使用的TimeUnit.MILLISECONDS而不是TimeUnit.NANOSECONDS,但是你会发现不管你用哪一个(或者其他的TimeUnit),这个程序的正确性是ok的,都会delay你所要的时间,例如分别使用这两种TimeUnit的输出:
If using MILLISECONDS:
current time in ms: 1369644922697
current time in ms: 1369644923697, element:e1
current time in ms: 1369644924197, element:e3
current time in ms: 1369644927697, element:e2
If using NANOSECONDS:
current time in ms: 1369645748910
current time in ms: 1369645749910, element:e1
current time in ms: 1369645750410, element:e3
current time in ms: 1369645753910, element:e2
那么会有什么问题呢?
Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue. Returns: the head of this queue Throws: java.lang.InterruptedException 181 182 public E take() throws InterruptedException { 183 final ReentrantLock lock = this.lock; 184 lock.lockInterruptibly(); 185 try { 186 for (;;) { 187 E first = q.peek(); 188 if (first == null) { 189 available.await(); 190 } else { 191 long delay = first.getDelay(TimeUnit.NANOSECONDS); 192 if (delay > 0) { 193 long tl = available.awaitNanos(delay); 194 } else { 195 E x = q.poll(); 196 assert x != null; 197 if (q.size() != 0) 198 available.signalAll(); // wake up other takers 199 return x; 200 201 } 202 } 203 } 204 } finally { 205 lock.unlock(); 206 } 207 }
看一下DelayQueue的take()方法会发现,在队列首对象的delay>0的时候,等待的时间单位是nanos(193行),所以如果我刚才getDelay()里面没有将ms转换成ns,那么数值会小很多,line 193 会很快执行,再次循环进行判断,delay仍然大于0,注意,总的等待时间是固定的,现在是每次wait的时间片变小了,所以循环的次数多了,造成一个结果就是cpu占用上升!
如果打印出每次delay的值便可以看到用nanos多做了多少次循环,读者可以自己看一下,呵呵。
遇到这个坑的人我google到有:
http://www.blogjava.net/killme2008/archive/2010/10/22/335897.html
发表评论
-
ssl 与 java 实例
2014-01-27 10:10 750http://www.iteye.com/topic/1125 ... -
Java NIO
2014-01-10 21:28 703看了这个java nio的教程,明白了什么是Selector. ... -
再谈Java的wait(), sleep(), notify()和notifyAll()
2013-07-25 10:59 1873一段时间不用java,这些概念就全混淆了,有必要彻底澄清一下, ... -
Why singleton is anti-pattern?
2013-07-03 10:12 873OO Test Other reasons? -
How to generate the serialVersionUID when you implement Serializable interface,j
2013-07-01 10:52 919http://docs.oracle.com/javase/6 ... -
Java Override的两个问题
2013-06-01 11:40 9261: 如果子类中的方法的参数是父类的方法的子类型,那么算不算o ... -
Java常用类API统计
2013-06-01 11:35 0String charAt(int) compareTo( ... -
How many string objects are created?
2013-06-01 10:18 1315This is a very common java inte ... -
[leetcode] Balanced Binary Tree
2013-04-28 14:08 1563Check if a binary tree is balan ... -
[leetcode] find median of two sorted arrays
2013-04-26 10:55 1437http://leetcode.com/onlinejudge ... -
[leetcode] word ladder
2013-04-25 15:05 2258Q: Given two words (start and ... -
[leetcode] word ladder II
2013-04-15 07:35 11646http://leetcode.com/onlinejudge ... -
[leetcode] Count and Say
2013-04-12 14:05 2241http://leetcode.com/onlinejudge ... -
Date/Time处理函数总结 [To Do]
2013-04-12 10:46 643几种我所用到的用来处理日期,时间的函数总结。 Perl 1 ... -
[leetcode] Palindrome Partition
2013-04-12 10:25 1308http://leetcode.com/onlinejudge ... -
[leetcode] Palindrome Partitioning II
2013-04-11 16:45 1495http://leetcode.com/onlinejudge ... -
Profiling your Java code using Spring
2013-03-05 15:02 664Quite good article!!! http://w ... -
Java的Generics的几点限制
2012-12-28 15:00 4709参见 http://docs.oracle.com/ ... -
Overriding Method Using Parameter That is a Subclass?
2012-12-27 22:14 877参见 http://www.coderanch.com/t/3 ... -
Java的Generics和c++的Template到底有什么不同?
2012-12-27 16:21 3185先了解Java的Generics: 根据Java的文档,Jav ...
相关推荐
java使用DelayQueue延迟队列和Redis缓存实现订单自动取消功能
DelayQueue的使用以及注意事项,这里需要由BlockingQueue的基本知识,一般的Queue的使用方法poll(),take(),drainTo()和offer(),put()这些应该懂。
主要为大家详细介绍了Java多线程并发开发之DelayQueue使用示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
DelayQueue、Redis结合使延迟、定时任务使用 DelayQueue、Redis结合使延迟、定时任务使用 DelayQueue、Redis结合使延迟、定时任务使用 源代码下载
学习视频,可以丰富java知识。能够获得更多的专业技能
DelayQueue是一个无界阻塞队列,只有在延迟期满时,才能从中提取元素。这篇文章主要介绍了springboot执行延时任务-DelayQueue的使用,需要的朋友可以参考下
主要给大家介绍了java利用delayedQueue实现本地的延迟队列的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。
volatile关键字的非原子性、volatile关键字的使用、AtomicInteger原子性操作、线程安全小例子:多个线程竞争问题、多个线程多个锁问题、创建一个缓存的线程池、多线程使用Vector或者HashTable的示例(简单线程同步...
4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 PriorityBlockingQueue 7. 同步队列 SynchronousQueue 8. 阻塞双端队列 BlockingDeque 9. 链阻塞双端队列 LinkedBlockingDeque ...
延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 PriorityBlockingQueue 7. 同步队列 SynchronousQueue 8. 阻塞双端队列 BlockingDeque 9. 链阻塞双端队列 LinkedBlockingDeque 10...
1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 ...
基于DelayQueue的简单的定时任务队列.zip Quick Start class Main { public static void main(String[] args) { // 初始化任务队列 JobScheduler scheduler = new JobScheduler("default"); // 向队列中提交任务...
本资源包含两个 pdf 文档,一本根据 Jakob Jenkov 最新博客 (http://tutorials.jenkov.com/java-util-concurrent/index.html) 整理的 java_util_concurrent_user_guide_en.pdf,一个中文翻译的 java_util_concurrent...
Agenda • Methodology and Process • Tools of Load Test • Tuning Components in the Software Stack ...> Java Virtual Machine > Application Container > Application Architecture • Future Performance Trend
本资源包含两个 pdf 文档,一本根据 Jakob Jenkov 最新博客 (http://tutorials.jenkov.com/java-util-concurrent/index.html) 整理的 java_util_concurrent_user_guide_en.pdf,一个中文翻译的 java_util_concurrent...
除了具有很好的并发性的Collections,java.util.concurrent还引入了其他一些预先构建的组件,它们可帮助您调整和执行多线程应用程序中的线程。
local delayQueue implemented by JDK & two kinds of distributed delayQueue based redis 1. 基本介绍 RedisSynDelayQueue 基于redis,并发情况下会加分布式锁,单线程场景(syn=false)性能较好, 并发场景性能较...
delayqueue:java自带延迟对了使用包 DelayMsg:延迟消息实体 DelayMsgHandler:延迟消息处理工具 paramvalid:空参检查包 CommonUtil:空参检查工具类 ParamNotNull:参数注解 RegistParam:参数实体 ...
数组阻塞队列ArrayBlockingQueue,延迟队列DelayQueue, 链阻塞队列 LinkedBlockingQueue,具有优先级的阻塞队列 PriorityBlockingQueue, 同步队列 SynchronousQueue,阻塞双端队列 BlockingDeque, 链阻塞双端队列 ...
具体代码参考