1、DeplayQueue延時無界阻塞隊列
在談到DelayQueue的使用和原理的時候,我們首先介紹一下DelayQueue,DelayQueue是一個無界阻塞隊列,只有在延遲期滿時才能從中提取元素。該隊列的頭部是延遲期滿后保存時間最長的Delayed元素。
DelayQueue阻塞隊列在我們系統(tǒng)開發(fā)中也常常會用到,例如:緩存系統(tǒng)的設(shè)計,緩存中的對象,超過了空閑時間,需要從緩存中移出;任務(wù)調(diào)度系統(tǒng),能夠準(zhǔn)確的把握任務(wù)的執(zhí)行時間。我們可能需要通過線程處理很多時間上要求很嚴(yán)格的數(shù)據(jù),如果使用普通的線程,我們就需要遍歷所有的對象,一個一個的檢查看數(shù)據(jù)是否過期等,首先這樣在執(zhí)行上的效率不會太高,其次就是這種設(shè)計的風(fēng)格也大大的影響了數(shù)據(jù)的精度。一個需要12:00點(diǎn)執(zhí)行的任務(wù)可能12:01才執(zhí)行,這樣對數(shù)據(jù)要求很高的系統(tǒng)有更大的弊端。由此我們可以使用DelayQueue。
下面將會對DelayQueue做一個介紹,然后舉個例子。并且提供一個Delayed接口的實現(xiàn)和Sample代碼。DelayQueue是一個BlockingQueue,其特化的參數(shù)是Delayed。(不了解BlockingQueue的同學(xué),先去了解BlockingQueue再看本文)Delayed擴(kuò)展了Comparable接口,比較的基準(zhǔn)為延時的時間值,Delayed接口的實現(xiàn)類getDelay的返回值應(yīng)為固定值(final)。DelayQueue內(nèi)部是使用PriorityQueue實現(xiàn)的。
DelayQueue=BlockingQueue+PriorityQueue+Delayed
DelayQueue的關(guān)鍵元素BlockingQueue、PriorityQueue、Delayed。可以這么說,DelayQueue是一個使用優(yōu)先隊列(PriorityQueue)實現(xiàn)的BlockingQueue,優(yōu)先隊列的比較基準(zhǔn)值是時間。
他們的基本定義如下
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 內(nèi)部的實現(xiàn)使用了一個優(yōu)先隊列。當(dāng)調(diào)用 DelayQueue 的 offer 方法時,把 Delayed 對象加入到優(yōu)先隊列 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 方法,把優(yōu)先隊列 q 的 first 拿出來(peek),如果沒有達(dá)到延時閥值,則進(jìn)行 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 實例應(yīng)用
Ps:為了具有調(diào)用行為,存放到 DelayDeque 的元素必須繼承 Delayed 接口。Delayed 接口使對象成為延遲對象,它使存放在 DelayQueue 類中的對象具有了激活日期。該接口強(qiáng)制執(zhí)行下列兩個方法。
一下將使用 Delay 做一個緩存的實現(xiàn)。其中共包括三個類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 接口的實現(xiàn):
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 的實現(xiàn),包括了 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 方法:
// 測試入口函數(shù)
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);
}
}
輸出結(jié)果為:
aaaa
null
我們看到上面的結(jié)果,如果超過延時的時間,那么緩存中數(shù)據(jù)就會自動丟失,獲得就為 null。
● 非阻塞隊列
首先我們要簡單的理解下什么是非阻塞隊列:
與阻塞隊列相反,非阻塞隊列的執(zhí)行并不會被阻塞,無論是消費(fèi)者的出隊,還是生產(chǎn)者的入隊。在底層,非阻塞隊列使用的是 CAS(compare and swap)來實現(xiàn)線程執(zhí)行的非阻塞。
● 非阻塞隊列簡單操作
與阻塞隊列相同,非阻塞隊列中的常用方法,也是出隊和入隊。
● offer():Queue 接口繼承下來的方法,實現(xiàn)隊列的入隊操作,不會阻礙線程的執(zhí)行,插入成功返回 true; 出隊方法:
● poll():移動頭結(jié)點(diǎn)指針,返回頭結(jié)點(diǎn)元素,并將頭結(jié)點(diǎn)元素出隊;隊列為空,則返回 null;
● peek():移動頭結(jié)點(diǎn)指針,返回頭結(jié)點(diǎn)元素,并不會將頭結(jié)點(diǎn)元素出隊;隊列為空,則返回 null;
首先我們需要了解悲觀鎖和樂觀鎖
悲觀鎖:假定并發(fā)環(huán)境是悲觀的,如果發(fā)生并發(fā)沖突,就會破壞一致性,所以要通過獨(dú)占鎖徹底禁止沖突發(fā)生。有一個經(jīng)典比喻,“如果你不鎖門,那么搗蛋鬼就回闖入并搞得一團(tuán)糟”,所以“你只能一次打開門放進(jìn)一個人,才能時刻盯緊他”。
樂觀鎖:假定并發(fā)環(huán)境是樂觀的,即雖然會有并發(fā)沖突,但沖突可發(fā)現(xiàn)且不會造成損害,所以,可以不加任何保護(hù),等發(fā)現(xiàn)并發(fā)沖突后再決定放棄操作還是重試。可類比的比喻為,“如果你不鎖門,那么雖然搗蛋鬼會闖入,但他們一旦打算破壞你就能知道”,所以“你大可以放進(jìn)所有人,等發(fā)現(xiàn)他們想破壞的時候再做決定”。通常認(rèn)為樂觀鎖的性能比悲觀所更高,特別是在某些復(fù)雜的場景。這主要由于悲觀鎖在加鎖的同時,也會把某些不會造成破壞的操作保護(hù)起來;而樂觀鎖的競爭則只發(fā)生在最小的并發(fā)沖突處,如果用悲觀鎖來理解,就是“鎖的粒度最小”。但樂觀鎖的設(shè)計往往比較復(fù)雜,因此,復(fù)雜場景下還是多用悲觀鎖。首先保證正確性,有必要的話,再去追求性能。
樂觀鎖的實現(xiàn)往往需要硬件的支持,多數(shù)處理器都都實現(xiàn)了一個CAS指令,實現(xiàn)“Compare And Swap”的語義(這里的swap是“換入”,也就是set),構(gòu)成了基本的樂觀鎖。CAS包含3個操作數(shù):
需要讀寫的內(nèi)存位置V
進(jìn)行比較的值A(chǔ)
擬寫入的新值B
當(dāng)且僅當(dāng)位置V的值等于A時,CAS才會通過原子方式用新值B來更新位置V的值;否則不會執(zhí)行任何操作。無論位置V的值是否等于A,都將返回V原有的值。一個有意思的事實是,“使用CAS控制并發(fā)”與“使用樂觀鎖”并不等價。CAS只是一種手段,既可以實現(xiàn)樂觀鎖,也可以實現(xiàn)悲觀鎖。樂觀、悲觀只是一種并發(fā)控制的策略。