Home >Java >javaTutorial >The use of DelayQueue in JAVA: blocking queue, delay queue
DelayQueue is an unbounded blocking queue from which elements can be extracted only when the delay expires. The head of the queue is the Delayed element that holds the longest time after the delay expires.
DelayQueue blocking queue is also often used in our system development, for example: the design of the cache system, the objects in the cache, exceed the idle time, need to be removed from the cache Move out; task scheduling system can accurately grasp the execution time of tasks. We may need to process a lot of time-critical data through threads. If we use ordinary threads, we need to traverse all objects and check one by one to see if the data has expired. First of all, the execution efficiency will not be too high. , Secondly, this design style also greatly affects the accuracy of the data. A task that needs to be executed at 12:00 may not be executed until 12:01, which has greater disadvantages for systems with high data requirements. From this we can use DelayQueue.
In order to have calling behavior, the elements stored in DelayDeque must implement the Delayed interface. The Delayed interface makes the object a delayed object, which gives the object stored in the DelayQueue class an activation date. This interface enforces the following two methods.
CompareTo(Delayed o):Delayed接口继承了Comparable接口,因此有了这个方法。 getDelay(TimeUnit unit):这个方法返回到激活日期的剩余时间,时间单位由单位参数指定。
Implement Delayed interface
This code: Compare the execution time after the contract is signed with the current time to achieve automatic execution of the contract at the point.
Thread starts, DelayQueue starts working
spring boot starts loading, initializes the data source and puts it in, And enable single thread
#Leave a record!
Related recommendations:
In-depth understanding of blocking queue containers in Java thread programming
ArrayBlockingQueue of concurrent package blocking queue
The above is the detailed content of The use of DelayQueue in JAVA: blocking queue, delay queue. For more information, please follow other related articles on the PHP Chinese website!