1 介绍
DelayQueue也是一个实现了BlockingQueue接口的“无边界”阻塞队列,但是该队列却是非常有意思和特殊的一个队列(存入DelayQueue中的数据元素会被延迟单位时间后才能消费),在DelayQueue中,元素也会根据优先级进行排序,这种排序可以是基于数据元素过期时间而进行的(比如,你可以将最快过期的数据元素排到队列头部,最晚过期的数据元素排到队尾)。
对于存入DelayQueue中的元素是有一定要求的:
- 元素类型必须是Delayed接口的子类
- 存入DelayQueue中的元素需要重写getDelay(TimeUnit unit)方法用于计算该元素距离过期的剩余时间
如果在消费DelayQueue时发现并没有任何一个元素到达过期时间,那么对该队列的读取操作会立即返回null值,或者使得消费线程进入阻塞
public interface Delayed extends Comparable<Delayed> {
/**
* Returns the remaining delay associated with this object, in the
* given time unit.
*
* @param unit the time unit
* @return the remaining delay; zero or negative values indicate
* that the delay has already elapsed
*/
long getDelay(TimeUnit unit);
}
2 基本使用
2.1 入门演示
DelayQueue中的元素都必须是Delayed接口的子类,该接口继承自Comparable接口,并且定义了一个唯一的接口方法getDelay
所以,首先需要实现Delayed接口,并且重写getDelay方法和compareTo方法。
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @author wyaoyao
* @date 2021/4/25 17:29
*/
public class DelayedEntry implements Delayed {
/**
* 元数据
*/
private final String value;
/**
* 用于计算失效时间
*/
private final long time;
public DelayedEntry(String metadata, long delayTime) {
this.value = metadata;
// 该元素可在(当前时间+delayTime)毫秒后消费,也就是说延迟消费delayTime毫秒
this.time = System.currentTimeMillis() + delayTime;
}
/**
* 重写getDelay方法,返回当前元素的延迟时间还剩余(remaining)多少个时间单位
*
* @param unit
* @return
*/
@Override
public long getDelay(TimeUnit unit) {
long delta = time - System.currentTimeMillis();
return unit.convert(delta, TimeUnit.MILLISECONDS);
}
/**
* 重写compareTo方法,队列头部的元素是最早即将失效的数据元素
*
* @param o
* @return
*/
@Override
public int compareTo(Delayed o) {
if (this.time < ((DelayedEntry) o).time) {
return -1;
} else if (this.time > ((DelayedEntry) o).time) {
return 1;
} else {
return 0;
}
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "DelayedEntry{" +
"value='" + value + '\'' +
", time=" + time +
'}';
}
}
public static void main(String[] args) {
// 定义DelayQueue,无需指定容量,因为DelayQueue是一个"无边界"的阻塞队列
DelayQueue<DelayedEntry> queue = new DelayQueue<>();
// 存入数据A,并制定在10000毫秒内失效
queue.put(new DelayedEntry("A",10_000L));
// 存入数据B,并制定在5000毫秒内失效
queue.put(new DelayedEntry("B",5_000L));
// 记录时间戳
final long timestamp = System.currentTimeMillis();
// poll是一个非阻塞的读取数据的方法,会立即返回
// 立即读取,因为没有数据过期,所以取出的是null
DelayedEntry poll = queue.poll();
System.out.println(poll == null); // true
// take方法会阻塞5000毫秒左右,因为此刻队列中最快达到过期条件的数据B只能在5000毫秒以后
try {
DelayedEntry value = queue.take();
System.out.println("value is " + value.getValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("大概阻塞时间: " + (System.currentTimeMillis() - timestamp));
// take方法会阻塞5000毫秒左右,因为此刻队列中最快达到过期条件的数据A只能在10000毫秒以后
try {
DelayedEntry value = queue.take();
System.out.println("value is " + value.getValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("大概阻塞时间: " + (System.currentTimeMillis() - timestamp));
}
输出:
true
value is B
大概阻塞时间: 5002
value is A
大概阻塞时间: 10002
2.2 读取DelayQueue中的数据
- remainingCapacity()方法始终返回Integer.MAX_VALUE
public static void main(String[] args) {
DelayQueue<DelayedEntry> queue = new DelayQueue<>();
System.out.println(queue.remainingCapacity() == Integer.MAX_VALUE); // true
queue.put(new DelayedEntry("A",10_000L));
queue.put(new DelayedEntry("B",10_000L));
System.out.println(queue.size()); // 2
System.out.println(queue.remainingCapacity() == Integer.MAX_VALUE); // true
}
- peek():非阻塞读方法,并且不存在延时,立即返回但并不移除DelayQueue的头部元素,当队列为空时返回null
public static void main(String[] args) {
DelayQueue<DelayedEntry> queue = new DelayQueue<>();
// 队列为空返回null
System.out.println(queue.peek());
queue.put(new DelayedEntry("A",10_000L));
queue.put(new DelayedEntry("B",10_000L));
// 不存在延时
System.out.println(queue.peek()); // A
}
- poll():非阻塞读方法,当队列为空或者队列头部元素还未到达过期时间时返回值为null,否则将会从队列头部立即将元素移除并返回。
public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayedEntry> queue = new DelayQueue<>();
// 队列为空返回null
System.out.println(queue.poll());
queue.put(new DelayedEntry("A", 10_000L));
queue.put(new DelayedEntry("B", 5_000L));
// 存在延时,由于没有过期元素,所以返回是null
System.out.println(queue.poll());
// 等个5s
TimeUnit.SECONDS.sleep(5);
System.out.println(queue.poll()); // B
TimeUnit.SECONDS.sleep(10);
System.out.println(queue.poll()); // A
}
- poll(long timeout, TimeUnit unit):阻塞读,最大阻塞单位时间,当达到阻塞时间后,此刻为空或者队列头部元素还未达到过期时间时返回值为null,否则将会立即从队列头部将元素移除并返回。
public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayedEntry> queue = new DelayQueue<>();
// 队列为空返回null
System.out.println(queue.poll());
queue.put(new DelayedEntry("A", 10_000L));
// 阻塞,但是只等待3s,3s后还没有过期元素,那就返回null,所以这里返回null
System.out.println(queue.poll(3,TimeUnit.SECONDS));
}
- take():阻塞式的读取方法,该方法会一直阻塞到队列中有元素,并且队列中的头部元素已达到过期时间,然后将其从队列中移除并返回。(入门案例中已经有相关代码演示了)
2.2 DelayQueue中写入数据
与PriorityBlockingQueue一样,DelayQueue中有关增加元素的所有方法都等价于offer(E e),并不存在针对队列临界值上限的控制,因此也不存在阻塞写的情况
// add 调用的也是offer
public boolean add(E e) {
return offer(e);
}
// put 调用的也是offer
public void put(E e) {
offer(e);
}
// 虽然也存在这么一个方法,但是底层调用的就是offer,也就说timeout这参数根本没有用
// 根本不存在阻塞写入的数据方式
public boolean offer(E e, long timeout, TimeUnit unit) {
return offer(e);
}
所以只需要知道offer就可以了
/**
向队列尾部写入新的数据,当队列已满时不会进入阻塞,并且会立即返回false。
**/
boolean offer(E e);