1、DeplayQueue延時無界阻塞隊列
在談到DelayQueue的使用和原理的時候,我們首先介紹一下DelayQueue,DelayQueue是一個無界阻塞隊列,只有在延遲期滿時才能從中提取元素。該隊列的頭部是延遲期滿后保存時間最長的Delayed元素。
DelayQueue阻塞隊列在我們系統開發中也常常會用到,例如:緩存系統的設計,緩存中的對象,超過了空閑時間,需要從緩存中移出;任務調度系統,能夠準確的把握任務的執行時間。我們可能需要通過線程處理很多時間上要求很嚴格的數據,如果使用普通的線程,我們就需要遍歷所有的對象,一個一個的檢查看數據是否過期等,首先這樣在執行上的效率不會太高,其次就是這種設計的風格也大大的影響了數據的精度。一個需要12:00點執行的任務可能12:01才執行,這樣對數據要求很高的系統有更大的弊端。由此我們可以使用DelayQueue。
下面將會對DelayQueue做一個介紹,然后舉個例子。并且提供一個Delayed接口的實現和Sample代碼。DelayQueue是一個BlockingQueue,其特化的參數是Delayed。(不了解BlockingQueue的同學,先去了解BlockingQueue再看本文)Delayed擴展了Comparable接口,比較的基準為延時的時間值,Delayed接口的實現類getDelay的返回值應為固定值(final)。DelayQueue內部是使用PriorityQueue實現的。
DelayQueue=BlockingQueue+PriorityQueue+Delayed
DelayQueue的關鍵元素BlockingQueue、PriorityQueue、Delayed。可以這么說,DelayQueue是一個使用優先隊列(PriorityQueue)實現的BlockingQueue,優先隊列的比較基準值是時間。
他們的基本定義如下
public interface Comparable<T> {
public int compareTo(T o);
}
public interface Delayed extends Comparable<Delayed> {
long getDelay(TimeUnit unit);
}
public class DelayQueue<E extends Delayed> implements BlockingQueue<E> {
private final PriorityQueue<E> q = new PriorityQueue<E>();
}
DelayQueue 內部的實現使用了一個優先隊列。當調用 DelayQueue 的 offer 方法時,把 Delayed 對象加入到優先隊列 q 中。如下:
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E first = q.peek();
q.offer(e);
if (first == null || e.compareTo(first) < 0)
available.signalAll();
return true;
} finally {
lock.unlock();
}
}
DelayQueue 的 take 方法,把優先隊列 q 的 first 拿出來(peek),如果沒有達到延時閥值,則進行 await處理。如下:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (; ; ) {
E first = q.peek();
if (first == null) {
available.await();
} else {
long delay = first.getDelay(TimeUnit.NANOSECONDS);
if (delay > 0) {
long tl = available.awaitNanos(delay);
} else {
E x = q.poll();
assert x != null;
if (q.size() != 0)
available.signalAll(); //wake up other takers return x;
}
}
}
} finally {
lock.unlock();
}
}
● DelayQueue 實例應用
Ps:為了具有調用行為,存放到 DelayDeque 的元素必須繼承 Delayed 接口。Delayed 接口使對象成為延遲對象,它使存放在 DelayQueue 類中的對象具有了激活日期。該接口強制執行下列兩個方法。
一下將使用 Delay 做一個緩存的實現。其中共包括三個類Pair、DelayItem、Cache
● Pair 類:
public class Pair<K, V> {
public K first;
public V second;
public Pair() {
}
public Pair(K first, V second) {
this.first = first;
this.second = second;
}
}
以下是對 Delay 接口的實現:
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class DelayItem<T> implements Delayed {
/**
* Base of nanosecond timings, to avoid wrapping
*/
private static final long NANO_ORIGIN = System.nanoTime();
/**
* Returns nanosecond time offset by origin
*/
final static long now() {
return System.nanoTime() - NANO_ORIGIN;
}
/**
* Sequence number to break scheduling ties, and in turn to guarantee FIFO order among tied
* entries.
*/
private static final AtomicLong sequencer = new AtomicLong(0);
/**
* Sequence number to break ties FIFO
*/
private final long sequenceNumber;
/**
* The time the task is enabled to execute in nanoTime units
*/
private final long time;
private final T item;
public DelayItem(T submit, long timeout) {
this.time = now() + timeout;
this.item = submit;
this.sequenceNumber = sequencer.getAndIncrement();
}
public T getItem() {
return this.item;
}
public long getDelay(TimeUnit unit) {
long d = unit.convert(time - now(), TimeUnit.NANOSECONDS); return d;
}
public int compareTo(Delayed other) {
if (other == this) // compare zero ONLY if same object return 0;
if (other instanceof DelayItem) {
DelayItem x = (DelayItem) other;
long diff = time - x.time;
if (diff < 0) return -1;
else if (diff > 0) return 1;
else if (sequenceNumber < x.sequenceNumber) return -1;
else
return 1;
}
long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ?0 :((d < 0) ?-1 :1);
}
}
以下是 Cache 的實現,包括了 put 和 get 方法
import javafx.util.Pair;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Cache<K, V> {
private static final Logger LOG = Logger.getLogger(Cache.class.getName());
private ConcurrentMap<K, V> cacheObjMap = new ConcurrentHashMap<K, V>();
private DelayQueue<DelayItem<Pair<K, V>>> q = new DelayQueue<DelayItem<Pair<K, V>>>();
private Thread daemonThread;
public Cache() {
Runnable daemonTask = new Runnable() {
public void run() {
daemonCheck();
}
};
daemonThread = new Thread(daemonTask);
daemonThread.setDaemon(true);
daemonThread.setName("Cache Daemon");
daemonThread.start();
}
private void daemonCheck() {
if (LOG.isLoggable(Level.INFO)) LOG.info("cache service started.");
for (; ; ) {
try {
DelayItem<Pair<K, V>> delayItem = q.take();
if (delayItem != null) {
// 超時對象處理
Pair<K, V> pair = delayItem.getItem();
cacheObjMap.remove(pair.first, pair.second); // compare and remove
}
} catch (InterruptedException e) {
if (LOG.isLoggable(Level.SEVERE)) LOG.log(Level.SEVERE, e.getMessage(), e);
break;
}
}
if (LOG.isLoggable(Level.INFO)) LOG.info("cache service stopped.");
}
// 添加緩存對象
public void put(K key, V value, long time, TimeUnit unit) {
V oldValue = cacheObjMap.put(key, value);
if (oldValue != null) q.remove(key);
long nanoTime = TimeUnit.NANOSECONDS.convert(time, unit);
q.put(new DelayItem<Pair<K, V>>(new Pair<K, V>(key, value), nanoTime));
}
public V get(K key) {
return cacheObjMap.get(key);
}
}
測試 main 方法:
// 測試入口函數
public static void main(String[] args) throws Exception {
Cache<Integer, String> cache = new Cache<Integer, String>();
cache.put(1, "aaaa", 3, TimeUnit.SECONDS);
Thread.sleep(1000 * 2);
{
String str = cache.get(1);
System.out.println(str);
}
Thread.sleep(1000 * 2);
{
String str = cache.get(1);
System.out.println(str);
}
}
輸出結果為:
aaaa
null
我們看到上面的結果,如果超過延時的時間,那么緩存中數據就會自動丟失,獲得就為 null。
● 非阻塞隊列
首先我們要簡單的理解下什么是非阻塞隊列:
與阻塞隊列相反,非阻塞隊列的執行并不會被阻塞,無論是消費者的出隊,還是生產者的入隊。在底層,非阻塞隊列使用的是 CAS(compare and swap)來實現線程執行的非阻塞。
● 非阻塞隊列簡單操作
與阻塞隊列相同,非阻塞隊列中的常用方法,也是出隊和入隊。
● offer():Queue 接口繼承下來的方法,實現隊列的入隊操作,不會阻礙線程的執行,插入成功返回 true; 出隊方法:
● poll():移動頭結點指針,返回頭結點元素,并將頭結點元素出隊;隊列為空,則返回 null;
● peek():移動頭結點指針,返回頭結點元素,并不會將頭結點元素出隊;隊列為空,則返回 null;
首先我們需要了解悲觀鎖和樂觀鎖
悲觀鎖:假定并發環境是悲觀的,如果發生并發沖突,就會破壞一致性,所以要通過獨占鎖徹底禁止沖突發生。有一個經典比喻,“如果你不鎖門,那么搗蛋鬼就回闖入并搞得一團糟”,所以“你只能一次打開門放進一個人,才能時刻盯緊他”。
樂觀鎖:假定并發環境是樂觀的,即雖然會有并發沖突,但沖突可發現且不會造成損害,所以,可以不加任何保護,等發現并發沖突后再決定放棄操作還是重試。可類比的比喻為,“如果你不鎖門,那么雖然搗蛋鬼會闖入,但他們一旦打算破壞你就能知道”,所以“你大可以放進所有人,等發現他們想破壞的時候再做決定”。通常認為樂觀鎖的性能比悲觀所更高,特別是在某些復雜的場景。這主要由于悲觀鎖在加鎖的同時,也會把某些不會造成破壞的操作保護起來;而樂觀鎖的競爭則只發生在最小的并發沖突處,如果用悲觀鎖來理解,就是“鎖的粒度最小”。但樂觀鎖的設計往往比較復雜,因此,復雜場景下還是多用悲觀鎖。首先保證正確性,有必要的話,再去追求性能。
樂觀鎖的實現往往需要硬件的支持,多數處理器都都實現了一個CAS指令,實現“Compare And Swap”的語義(這里的swap是“換入”,也就是set),構成了基本的樂觀鎖。CAS包含3個操作數:
需要讀寫的內存位置V
進行比較的值A
擬寫入的新值B
當且僅當位置V的值等于A時,CAS才會通過原子方式用新值B來更新位置V的值;否則不會執行任何操作。無論位置V的值是否等于A,都將返回V原有的值。一個有意思的事實是,“使用CAS控制并發”與“使用樂觀鎖”并不等價。CAS只是一種手段,既可以實現樂觀鎖,也可以實現悲觀鎖。樂觀、悲觀只是一種并發控制的策略。