首先延時隊列的發現是基於一個實際場景:如何處理超時的訂單
這個問題很容易想到解決方案
(1)寫一個定時任務,輪詢超時的訂單(缺點:性能消耗過大,對數據庫造成壓力)
(2)放入延時隊列當中
那麼我就選擇一下延時隊列,看一下java的實現吧。
貼出一個入門的博客:https://www.cnblogs.com/barrywxx/p/8525907.html
然後我們就以這個博客來入手源碼
1.首先看下如何使用
public static void main(String[] args) {
// 創建延時隊列
DelayQueue<Message> queue = new DelayQueue<Message>();
// 添加延時消息,m1 延時3s
Message m1 = new Message(1, "world", 3000);
// 添加延時消息,m2 延時10s
Message m2 = new Message(2, "hello", 10000);
//將延時消息放到延時隊列中
queue.offer(m2);
queue.offer(m1);
// 啓動消費線程 消費添加到延時隊列中的消息,前提是任務到了延期時間
ExecutorService exec = Executors.newFixedThreadPool(1);
exec.execute(new Consumer(queue));
exec.shutdown();
}
public class Consumer implements Runnable {
// 延時隊列 ,消費者從其中獲取消息進行消費
private DelayQueue<Message> queue;
public Consumer(DelayQueue<Message> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
Message take = queue.take();
System.out.println("消費消息id:" + take.getId() + " 消息體:" + take.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
那麼從上面可以看得出來,最基礎的兩個方法便是queue.offer(X),queue.take();
1.那麼就從offer()開始看起
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
//這裏DelayQueue其實內置了一個隊列,大部分功能是沿用了優先級隊列
//優先級隊列大致就是講的是 1 2 3 4 5 6 7這7個數你隨便指定先後順序放入
//都只會有一種結果
//private final PriorityQueue<E> q = new PriorityQueue<E>();
q.offer(e);
//如果e是隊首的話就喚醒其餘等待線程
if (q.peek() == e) {
leader = null;
available.signal();
}
return true;
} finally {
lock.unlock();
}
}
//接着看q.offer(e);
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
//這裏是擴容操作
if (i >= queue.length)
grow(i + 1);
size = i + 1;
//隊列第一個沒有的話,就直接放入
if (i == 0)
queue[0] = e;
//繼續看
else
siftUp(i, e);
return true;
}
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
//一個一個的對比,一般來說是自己實現compareTo的實現
//一般就是對比時間
private void siftUpUsingComparator(int k, E x) {
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = x;
}
2.take()
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
//peek(): return (size == 0) ? null : (E) queue[0];
//就是獲取第一個元素
E first = q.peek();
if (first == null)
//availabe是一個condition
available.await();
else {
//對比當前時間是否達到
long delay = first.getDelay(NANOSECONDS);
//已經到了
if (delay <= 0)
//返回頭結點,並將其移除
return q.poll();
first = null; // don't retain ref while waiting
//leader是用來提高效率的
//因爲前面是lock.lockInterruptibly(),
//可能存在多個線程一起去take()
//所以避開過多線程一起操作
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;
try {
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
if (leader == null && q.peek() != null)
available.signal();
lock.unlock();
}
}