書上寫的:
Future 模式是多線程開發中很是常見的一種設計模式,它的核心思想是異步調用。當咱們須要調用一一個函數方法時,若是這個函數執行很慢,那麼咱們就要進行等待。但有時候,咱們可能並不急着要結果。所以,咱們可讓被調者當即返回,讓它在後臺慢慢處理這個請求。對於調用者來講,則能夠先處理一些其餘任務,在真正須要數據的場合再去嘗試得到須要的數據。 Future 模式有點相似在網上買東西。若是咱們在網上下單買了一一個手機,當咱們支付完成後,手機並無辦法當即送到家裏,可是在電腦上會當即產生一個訂單。這個訂單就是未來發貨或者領取手機的重要憑證,這個憑證也就是Future模式中會給出的一個契約。在支付活動結束後,你們不會傻傻地等着手機到來,而是能夠各忙各的。而這張訂單就成爲了商家配貨、發貨的驅動力。固然,這一切你並不用關心。你要作的,只是在快遞上門時,開一下門,拿一下貨而已。 對於Future模式來講,雖然它沒法當即給出你須要的數據。可是,它會返回給你一一個契約,未來,你能夠憑藉着這個契約去從新獲取你須要的信息。
java
如圖,顯示了經過傳統的同步方法,調用一段比較耗時的程序。客戶端發出call請求,這個請求須要至關長一段時間才能返回。客戶端一直等待,直到數據返回,隨後, 再進行其餘任務的處理。 git
下圖是future模式程序員
package com.test.version3future; 1. @author: zhangzeli 2. @date 20:35 2018/4/20 3. [博客版權](http://https://my.oschina.net/u/3703858/blog/1798696) 4. [項目地址 ](https://gitee.com/zhangzeli/java-concurrent) public class CommonCook { // 網購廚具線程 static class OnlineShopping extends Thread { private Chuju chuju; @Override public void run() { System.out.println("第一步:下單"); System.out.println("第一步:等待送貨"); try { Thread.sleep(5000); // 模擬送貨時間 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("第一步:快遞送到"); chuju = new Chuju(); } } // 用廚具烹飪食材 static void cook(Chuju chuju, Shicai shicai) {} // 廚具類 static class Chuju {} // 食材類 static class Shicai {} public static void main(String[] args) throws InterruptedException { long startTime = System.currentTimeMillis(); // 第一步 網購廚具 OnlineShopping thread = new OnlineShopping(); thread.start(); thread.join(); // 保證廚具送到 // 第二步 去超市購買食材 Thread.sleep(2000); // 模擬購買食材時間 Shicai shicai = new Shicai(); System.out.println("第二步:食材到位"); // 第三步 用廚具烹飪食材 System.out.println("第三步:開始展示廚藝"); cook(thread.chuju, shicai); System.out.println("總共用時" + (System.currentTimeMillis() - startTime) + "ms"); } }
運行結果:數據庫
能夠看到,多線程已經失去了意義。在廚具送到期間,咱們不能幹任何事。對應代碼,就是調用join方法阻塞主線程。設計模式
有人問了,不阻塞主線程行不行???數據結構
不行!!!多線程
從代碼來看的話,run方法不執行完,屬性chuju就沒有被賦值,仍是null。換句話說,沒有廚具,怎麼作飯。Java如今的多線程機制,核心方法run是沒有返回值的;若是要保存run方法裏面的計算結果,必須等待run方法計算完,不管計算過程多麼耗時。 面對這種尷尬的處境,程序員就會想:在子線程run方法計算的期間,能不能在主線程裏面繼續異步執行??? Where there is a will,there is a way!!! 這種想法的核心就是Future模式,下面先應用一下Java本身實現的Future模式。
併發
package com.test.version3future; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; 1. @author: zhangzeli 2. @date 20:35 2018/4/20 3. [博客版權](http://https://my.oschina.net/u/3703858/blog/1798696) 4. [項目地址 ](https://gitee.com/zhangzeli/java-concurrent) public class FutureCook { // 用廚具烹飪食材 static void cook(Chuju chuju, Shicai shicai) {} // 廚具類 static class Chuju {} // 食材類 static class Shicai {} public static void main(String[] args) throws InterruptedException, ExecutionException { long startTime = System.currentTimeMillis(); // 第一步 網購廚具 Callable<Chuju> onlineShopping = new Callable<Chuju>() { @Override public Chuju call() throws Exception { System.out.println("第一步:下單"); System.out.println("第一步:等待送貨"); Thread.sleep(5000); // 模擬送貨時間 System.out.println("第一步:快遞送到"); return new Chuju(); } }; FutureTask<Chuju> task = new FutureTask<Chuju>(onlineShopping); new Thread(task).start(); // 第二步 去超市購買食材 Thread.sleep(2000); // 模擬購買食材時間 Shicai shicai = new Shicai(); System.out.println("第二步:食材到位"); // 第三步 用廚具烹飪食材 if (!task.isDone()) { // 聯繫快遞員,詢問是否到貨 System.out.println("第三步:廚具還沒到,心情好就等着(心情很差就調用cancel方法取消訂單)"); } Chuju chuju = task.get(); System.out.println("第三步:廚具到位,開始展示廚藝"); cook(chuju, shicai); System.out.println("總共用時" + (System.currentTimeMillis() - startTime) + "ms"); } }
運行結果:異步
1)把耗時的網購廚具邏輯,封裝到了一個Callable的call方法裏面。ide
public interface Future<V> { /**若是任務還沒開始,執行cancel(...)方法將返回false; 若是任務已經啓動,執行cancel(true)方法將以中斷執行此任務線程的方式來試圖中止任務,若是中止成功,返回true; 當任務已經啓動,執行cancel(false)方法將不會對正在執行的任務線程產生影響(讓線程正常執行到完成),此時返回false; 當任務已經完成,執行cancel(...)方法將返回false。mayInterruptRunning參數表示是否中斷執行中的線程。 **/ boolean cancel(boolean mayInterruptIfRunning); //若是任務完成前被取消,則返回true。 boolean isCancelled(); //若是任務執行結束,不管是正常結束或是中途取消仍是發生異常,都返回true。 boolean isDone(); //獲取異步執行的結果,若是沒有結果可用,此方法會阻塞直到異步計算完成。 V get() throws InterruptedException, ExecutionException; //獲取異步執行結果,若是沒有結果可用,此方法會阻塞,可是會有時間限制,若是阻塞時間超 V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; } public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; } // Callable接口能夠看做是Runnable接口的補充,call方法帶有返回值,而且能夠拋出異常。
2)把Callable實例看成參數,生成一個FutureTask的對象,而後把這個對象看成一個Runnable,做爲參數另起線程。
public class FutureTask<V> implements RunnableFuture<V>{} public interface RunnableFuture<V> extends Runnable, Future<V>{} public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; } //這個繼承體系中的核心接口是Future。Future的核心思想是:一個方法f, //計算過程可能很是耗時,等待f返回,顯然不明智。能夠在調用f的時候,立馬返回一個Future, //能夠經過Future這個數據結構去控制方法f的計算過程。
3)在第三步裏面,調用了isDone方法查看狀態,而後直接調用task.get方法獲取廚具,不過這時還沒送到,因此仍是會等待3秒。對比第一段代碼的執行結果,這裏咱們節省了2秒。這是由於在快遞員送貨期間,咱們去超市購買食材,這兩件事在同一時間段內異步執行。
經過以上3步,咱們就完成了對Java原生Future模式最基本的應用。下面具體分析下FutureTask的實現,先看JDK8的,再比較一下JDK6的實現。 既然FutureTask也是一個Runnable,那就看看它的run方法
public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callable<V> c = callable; // 這裏的callable是從構造方法裏面傳人的 if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); // 保存call方法拋出的異常 } if (ran) set(result); // 保存call方法的執行結果 } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }
先看try語句塊裏面的邏輯,發現run方法的主要邏輯就是運行Callable的call方法,而後將保存結果或者異常(用的一個屬性result)。這裏比較難想到的是,將call方法拋出的異常也保存起來了。
這裏表示狀態的屬性state是個什麼鬼
* Possible state transitions: * NEW -> COMPLETING -> NORMAL * NEW -> COMPLETING -> EXCEPTIONAL * NEW -> CANCELLED * NEW -> INTERRUPTING -> INTERRUPTED */ private volatile int state; private static final int NEW = 0; private static final int COMPLETING = 1; private static final int NORMAL = 2; private static final int EXCEPTIONAL = 3; private static final int CANCELLED = 4; private static final int INTERRUPTING = 5; private static final int INTERRUPTED = 6;
把FutureTask看做一個Future,那麼它的做用就是控制Callable的call方法的執行過程,在執行的過程當中天然會有狀態的轉換:
1)一個FutureTask新建出來,state就是NEW狀態;COMPETING和INTERRUPTING用的進行時,
表示瞬時狀態,存在時間極短(爲何要設立這種狀態???不解);
NORMAL表明順利完成;EXCEPTIONAL表明執行過程出現異常;CANCELED表明執行過程被取消;
INTERRUPTED被中斷
2)執行過程順利完成:NEW -> COMPLETING -> NORMAL
3)執行過程出現異常:NEW -> COMPLETING -> EXCEPTIONAL
4)執行過程被取消:NEW -> CANCELLED
5)執行過程當中,線程中斷:NEW -> INTERRUPTING -> INTERRUPTED
再看看get方法的實現:
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); } private int awaitDone(boolean timed, long nanos) throws InterruptedException { final long deadline = timed ? System.nanoTime() + nanos : 0L; WaitNode q = null; boolean queued = false; for (;;) { if (Thread.interrupted()) { removeWaiter(q); throw new InterruptedException(); } int s = state; if (s > COMPLETING) { if (q != null) q.thread = null; return s; } else if (s == COMPLETING) // cannot time out yet Thread.yield(); else if (q == null) q = new WaitNode(); else if (!queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); else if (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { removeWaiter(q); return state; } LockSupport.parkNanos(this, nanos); } else LockSupport.park(this); } }
get方法的邏輯很簡單,若是call方法的執行過程已完成,就把結果給出去;若是未完成,就將當前線程掛起等待。awaitDone方法裏面死循環的邏輯,推演幾遍就能弄懂;它裏面掛起線程的主要創新是定義了WaitNode類,來將多個等待線程組織成隊列,這是與JDK6的實現最大的不一樣。
最後來看看,Future模式衍生出來的更高級的應用。
再上一個場景:咱們本身寫一個簡單的數據庫鏈接池,可以複用數據庫鏈接,而且能在高併發狀況下正常工做。
package test; import java.util.concurrent.ConcurrentHashMap; public class ConnectionPool { private ConcurrentHashMap<String, Connection> pool = new ConcurrentHashMap<String, Connection>(); public Connection getConnection(String key) { Connection conn = null; if (pool.containsKey(key)) { conn = pool.get(key); } else { conn = createConnection(); pool.putIfAbsent(key, conn); } return conn; } public Connection createConnection() { return new Connection(); } class Connection {} }
咱們用了ConcurrentHashMap,這樣就沒必要把getConnection方法置爲synchronized(固然也能夠用Lock),當多個線程同時調用getConnection方法時,性能大幅提高。
貌似很完美了,可是有可能致使多餘鏈接的建立,推演一遍:
某一時刻,同時有3個線程進入getConnection方法,調用pool.containsKey(key)都返回false,而後3個線程各自都建立了鏈接。雖然ConcurrentHashMap的put方法只會加入其中一個,但仍是生成了2個多餘的鏈接。若是是真正的數據庫鏈接,那會形成極大的資源浪費。
因此,咱們如今的難點是:如何在多線程訪問getConnection方法時,只執行一次createConnection。
結合以前Future模式的實現分析:當3個線程都要建立鏈接的時候,若是隻有一個線程執行createConnection方法建立一個鏈接,其它2個線程只須要用這個鏈接就好了。再延伸,把createConnection方法放到一個Callable的call方法裏面,而後生成FutureTask。咱們只須要讓一個線程執行FutureTask的run方法,其它的線程只執行get方法就行了。
上代碼:
package test; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class ConnectionPool { private ConcurrentHashMap<String, FutureTask<Connection>> pool = new ConcurrentHashMap<String, FutureTask<Connection>>(); public Connection getConnection(String key) throws InterruptedException, ExecutionException { FutureTask<Connection> connectionTask = pool.get(key); if (connectionTask != null) { return connectionTask.get(); } else { Callable<Connection> callable = new Callable<Connection>() { @Override public Connection call() throws Exception { return createConnection(); } }; FutureTask<Connection> newTask = new FutureTask<Connection>(callable); connectionTask = pool.putIfAbsent(key, newTask); if (connectionTask == null) { connectionTask = newTask; connectionTask.run(); } return connectionTask.get(); } } public Connection createConnection() { return new Connection(); } class Connection { } }
推演一遍:當3個線程同時進入else語句塊時,各自都建立了一個FutureTask, 可是ConcurrentHashMap只會加入其中一個。第一個線程執行pool.putIfAbsent方法後返回null, 而後connectionTask被賦值,接着就執行run方法去建立鏈接,最後get。後面的線程執行pool.putIfAbsent方法不會返回null, 就只會執行get方法。在併發的環境下,經過FutureTask做爲中間轉換,成功實現了讓某個方法只被一個線程執行。
下一篇 會講到加強的future模式CompletableFuture