1、DeplayQueue延時無界阻塞隊列
在談到DelayQueue的使用和原理的時候,我們首先介紹一下DelayQueue,DelayQueue是一個無界阻塞隊列,只有在延遲期滿時才能從中提取元素。該隊列的頭部是延遲期滿后保存時間最長的Delayed元素。 (推薦學(xué)習(xí):java面試題目)
DelayQueue阻塞隊列在我們系統(tǒng)開發(fā)中也常常會用到,例如:緩存系統(tǒng)的設(shè)計,緩存中的對象,超過了空閑時間,需要從緩存中移出;任務(wù)調(diào)度系統(tǒng),能夠準確的把握任務(wù)的執(zhí)行時間。我們可能需要通過線程處理很多時間上要求很嚴格的數(shù)據(jù)。
如果使用普通的線程,我們就需要遍歷所有的對象,一個一個的檢查看數(shù)據(jù)是否過期等,首先這樣在執(zhí)行上的效率不會太高,其次就是這種設(shè)計的風(fēng)格也大大的影響了數(shù)據(jù)的精度。一個需要12:00點執(zhí)行的任務(wù)可能12:01才執(zhí)行,這樣對數(shù)據(jù)要求很高的系統(tǒng)有更大的弊端。由此我們可以使用DelayQueue。
立即學(xué)習(xí)“Java免費學(xué)習(xí)筆記(深入)”;
下面將會對DelayQueue做一個介紹,然后舉個例子。并且提供一個Delayed接口的實現(xiàn)和Sample代碼。DelayQueue是一個BlockingQueue,其特化的參數(shù)是Delayed。
(不了解BlockingQueue的同學(xué),先去了解BlockingQueue再看本文)Delayed擴展了Comparable接口,比較的基準為延時的時間值,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)先隊列的比較基準值是時間。
他們的基本定義如下
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)先隊列。當調(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),如果沒有達到延時閥值,則進行 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 類中的對象具有了激活日期。該接口強制執(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。
2、并發(fā)(Collection)隊列-非阻塞隊列
非阻塞隊列
首先我們要簡單的理解下什么是非阻塞隊列:
與阻塞隊列相反,非阻塞隊列的執(zhí)行并不會被阻塞,無論是消費者的出隊,還是生產(chǎn)者的入隊。在底層,非阻塞隊列使用的是 CAS(compare and swap)來實現(xiàn)線程執(zhí)行的非阻塞。
非阻塞隊列簡單操作
與阻塞隊列相同,非阻塞隊列中的常用方法,也是出隊和入隊。
offer():Queue 接口繼承下來的方法,實現(xiàn)隊列的入隊操作,不會阻礙線程的執(zhí)行,插入成功返回 true; 出隊方法:
poll():移動頭結(jié)點指針,返回頭結(jié)點元素,并將頭結(jié)點元素出隊;隊列為空,則返回 null;
peek():移動頭結(jié)點指針,返回頭結(jié)點元素,并不會將頭結(jié)點元素出隊;隊列為空,則返回 null;
3、非阻塞算法CAS
首先我們需要了解悲觀鎖和樂觀鎖
悲觀鎖:假定并發(fā)環(huán)境是悲觀的,如果發(fā)生并發(fā)沖突,就會破壞一致性,所以要通過獨占鎖徹底禁止沖突發(fā)生。有一個經(jīng)典比喻,“如果你不鎖門,那么搗蛋鬼就回闖入并搞得一團糟”,所以“你只能一次打開門放進一個人,才能時刻盯緊他”。
樂觀鎖:假定并發(fā)環(huán)境是樂觀的,即雖然會有并發(fā)沖突,但沖突可發(fā)現(xiàn)且不會造成損害,所以,可以不加任何保護,等發(fā)現(xiàn)并發(fā)沖突后再決定放棄操作還是重試??深惐鹊谋扔鳛椋叭绻悴绘i門,那么雖然搗蛋鬼會闖入,但他們一旦打算破壞你就能知道”,所以“你大可以放進所有人,等發(fā)現(xiàn)他們想破壞的時候再做決定”。
通常認為樂觀鎖的性能比悲觀所更高,特別是在某些復(fù)雜的場景。這主要由于悲觀鎖在加鎖的同時,也會把某些不會造成破壞的操作保護起來;而樂觀鎖的競爭則只發(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
進行比較的值A(chǔ)
擬寫入的新值B
當且僅當位置V的值等于A時,CAS才會通過原子方式用新值B來更新位置V的值;否則不會執(zhí)行任何操作。無論位置V的值是否等于A,都將返回V原有的值。一個有意思的事實是,“使用CAS控制并發(fā)”與“使用樂觀鎖”并不等價。CAS只是一種手段,既可以實現(xiàn)樂觀鎖,也可以實現(xiàn)悲觀鎖。樂觀、悲觀只是一種并發(fā)控制的策略。
以上就是java多線程和并發(fā)面試題目(1~3題,附答案)的詳細內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
java怎么學(xué)習(xí)?java怎么入門?java在哪學(xué)?java怎么學(xué)才快?不用擔心,這里為大家提供了java速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://m.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號