徹底理解Java的Future模式

來源:互聯網
上載者:User

標籤:over   www.   ==   完美   main   orm   exec   html   代碼   

轉載自:http://www.cnblogs.com/cz123/p/7693064.html

先上一個情境:假如你突然想做飯,但是沒有廚具,也沒有食材。網上購買廚具比較方便,食材去超市買更放心。

實現分析:在快遞員送廚具的期間,我們肯定不會閑著,可以去超市買食材。所以,在主線程裡面另起一個子線程去網購廚具。

但是,子線程執行的結果是要返回廚具的,而run方法是沒有傳回值的。所以,這才是痛點,需要好好考慮一下。

類比代碼1:

package test;public class CommonCook {    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");    }        // 網購廚具線程    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 {}} 

運行結果:

第一步:下單第一步:等待送貨第一步:快遞送到第二步:食材到位第三步:開始展現廚藝總共用時7013ms

可以看到,多線程已經失去了意義。在廚具送到期間,我們不能幹任何事。對應代碼,就是調用join方法阻塞主線程。

有人問了,不阻塞主線程行不行???

不行!!!

從代碼來看的話,run方法不執行完,屬性chuju就沒有被賦值,還是null。換句話說,沒有廚具,怎麼做飯。

Java現在的多線程機制,核心方法run是沒有傳回值的;如果要儲存run方法裡面的計算結果,必須等待run方法計算完,無論計算過程多麼耗時。

面對這種尷尬的處境,程式員就會想:在子線程run方法計算的期間,能不能在主線程裡面繼續非同步執行???

Where there is a will,there is a way!!!

這種想法的核心就是Future模式,下面先應用一下Java自己實現的Future模式。

類比代碼2:

package test;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class FutureCook {    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");    }        //  用廚具烹飪食材    static void cook(Chuju chuju, Shicai shicai) {}        // 廚具類    static class Chuju {}        // 食材類    static class Shicai {}}

運行結果:

第一步:下單第一步:等待送貨第二步:食材到位第三步:廚具還沒到,心情好就等著(心情不好就調用cancel方法取消訂單)第一步:快遞送到第三步:廚具到位,開始展現廚藝總共用時5005ms

 可以看見,在快遞員送廚具的期間,我們沒有閑著,可以去買食材;而且我們知道廚具到沒到,甚至可以在廚具沒到的時候,取消訂單不要了。

好神奇,有沒有。

下面具體分析一下第二段代碼:

1)把耗時的網購廚具邏輯,封裝到了一個Callable的call方法裡面。

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的計算過程。

這裡的控制包括:

get方法:擷取計算結果(如果還沒計算完,也是必須等待的)

cancel方法:還沒計算完,可以取消計算過程

isDone方法:判斷是否計算完

isCancelled方法:判斷計算是否被取消

這些介面的設計很完美,FutureTask的實現註定不會簡單,後面再說。

 

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

代碼中狀態判斷、CAS操作等細節,請讀者自己閱讀。

再看看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的實現最大的不同。

掛起的線程何時被喚醒:

    private void finishCompletion() {        // assert state > COMPLETING;        for (WaitNode q; (q = waiters) != null;) {            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {                for (;;) {                    Thread t = q.thread;                    if (t != null) {                        q.thread = null;                        LockSupport.unpark(t); // 喚醒線程                    }                    WaitNode next = q.next;                    if (next == null)                        break;                    q.next = null; // unlink to help gc                    q = next;                }                break;            }        }        done();        callable = null;        // to reduce footprint    }

 以上就是JDK8的大體實現邏輯,像cancel、set等方法,也請讀者自己閱讀。

再來看看JDK6的實現。

JDK6的FutureTask的基本操作都是通過自己的內部類Sync來實現的,而Sync繼承自AbstractQueuedSynchronizer這個出鏡率極高的並發工具類

       /** State value representing that task is running */        private static final int RUNNING   = 1;        /** State value representing that task ran */        private static final int RAN       = 2;        /** State value representing that task was cancelled */        private static final int CANCELLED = 4;        /** The underlying callable */        private final Callable<V> callable;        /** The result to return from get() */        private V result;        /** The exception to throw from get() */        private Throwable exception;

 裡面的狀態只有基本的幾個,而且計算結果和異常是分開儲存的。

        V innerGet() throws InterruptedException, ExecutionException {            acquireSharedInterruptibly(0);            if (getState() == CANCELLED)                throw new CancellationException();            if (exception != null)                throw new ExecutionException(exception);            return result;        }

這個get方法裡面處理等待線程隊列的方式是調用了acquireSharedInterruptibly方法,看過我之前幾篇部落格文章的讀者應該非常熟悉了。其中的等待線程隊列、線程掛起和喚醒等邏輯,這裡不再贅述,如果不明白,請出門左轉。

 

最後來看看,Future模式衍生出來的更進階的應用。

再上一個情境:我們自己寫一個簡單的資料庫連接池,能夠複用資料庫連接,並且能在高並發情況下正常工作。

實現代碼1:

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作為中間轉換,成功實現了讓某個方法只被一個線程執行。

就這麼多吧,真是嘔心瀝血啊!!!哈哈

徹底理解Java的Future模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.