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;
}
}
}
标签:return,包装,long,DelayQueueTarget,private,DelayQueue,Java,public,currentSize
From: https://www.cnblogs.com/IC1101/p/17138262.html