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