Java 併發編程——Callable+Future+FutureTask

Java 併發編程系列文章

Java 併發基礎——線程安全性html

Java 併發編程——Callable+Future+FutureTaskjava

java 併發編程——Thread 源碼從新學習node

java併發編程——經過ReentrantLock,Condition實現銀行存取款編程

Java併發編程——BlockingQueue安全

Java 併發編程——Executor框架和線程池原理併發


 

 

項目中常常有些任務須要異步(提交到線程池中)去執行,而主線程每每須要知道異步執行產生的結果,這時咱們要怎麼作呢?用runnable是沒法實現的,咱們須要用callable實現。app

 

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class AddTask implements Callable<Integer> {

    private int a,b;

    public AddTask(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer call() throws Exception {
        Integer result = a + b;
        return result;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        //JDK目前爲止返回的都是FutureTask的實例 
        Future<Integer> future = executor.submit(new AddTask(1, 2));
        Integer result = future.get();// 只有當future的狀態是已完成時(future.isDone() = true),get()方法纔會返回 
    }
}

 

Callable接口                                                                                                     

Callable接口Runable接口可謂是兄弟關係,只不過Callable是帶返回值的。框架

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;
}

 

Future 接口                                                                                                        

接口函數及含義 :public interface Future<V>less

 boolean  cancel(boolean mayInterruptIfRunning)異步

取消當前執行的任務,若是已經執行完畢或者已經被取消/因爲某種緣由不能被取消 則取消任務失敗。

參數mayInterruptIfRunning: 當任務正在執行,若是參數爲true ,則嘗試中斷任務,不然讓任務繼續執行知道結束。

 
boolean isCancelled()
Returns {@code true} if this task was cancelled before it completed
* normally.
 
boolean isDone();
/**
* Returns {@code true} if this task completed.
*
* Completion may be due to normal termination, an exception, or
* cancellation -- in all of these cases, this method will return
* {@code true}.
*
* @return {@code true} if this task completed
*/
 

V get() throws InterruptedException, ExecutionException;

/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
由註釋能夠看出,當沒有執行完成時,須要等待任務執行完成了纔會將計算結果返回。

 

V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;

Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.

若是等待的時間超過設置的時間則會報 TimeoutException異常

FutureTask                                                                                                     

public class FutureTask<V> implements RunnableFuture<V>

由定義能夠看出它實現了RunnableFuture接口,那麼這個接口又是什麼呢?看下面的接口定義,其實很簡單

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /** * Sets this Future to the result of its computation * unless it has been cancelled. */
    void run();
}

再回到FutureTask,它其實就是實現了Runnable和Future接口,FutureTask的執行是 狀態轉換的過程,源碼中有七種狀態以下:

* 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剛剛被建立時,它的狀態是NEW,其它狀態查看源碼。

其它成員變量:

/** The underlying callable; nulled out after running */
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

callable是待執行的任務,FutureTask 的 run()函數中執行callable中的任務。

outcome : 是callable的執行結果,當正常執行完成後會將結果set到outcome中

runner:是執行callable 的線程

WaitNode : 是的受阻塞的線程鏈表,當cancel一個任務後,阻塞的線程會被喚醒。

 

構造函數:

public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; this.state = NEW;       // ensure visibility of callable
 } public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); this.state = NEW;       // ensure visibility of callable
}

從構造函數能夠看出,不光能夠經過callable構造FutureTask還能夠經過Runnable接口轉化爲callable來構造。關鍵函數爲黃色標記部分,Executors中的實現源碼以下:

/** * A callable that runs given task and returns given result. */
    private static final class RunnableAdapter<T> implements Callable<T> { private final Runnable task; private final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; } }

這裏面不懂result到底有什麼意義,明明就是預先設置好的。

 

其它具體的方法說明這裏再也不細說,裏面用到了不少sun.misc.Unsafe中的方法以及其餘SDK底層接口,後續有時間再學習。下面貼出了整個源碼及說明

public class FutureTask<V> implements RunnableFuture<V> {
    /* * Revision notes: This differs from previous versions of this * class that relied on AbstractQueuedSynchronizer, mainly to * avoid surprising users about retaining interrupt status during * cancellation races. Sync control in the current design relies * on a "state" field updated via CAS to track completion, along * with a simple Treiber stack to hold waiting threads. * * Style note: As usual, we bypass overhead of using * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics. */

    /** * The run state of this task, initially NEW. The run state * transitions to a terminal state only in methods set, * setException, and cancel. During completion, state may take on * transient values of COMPLETING (while outcome is being set) or * INTERRUPTING (only while interrupting the runner to satisfy a * cancel(true)). Transitions from these intermediate to final * states use cheaper ordered/lazy writes because values are unique * and cannot be further modified. * * 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;

    /** The underlying callable; nulled out after running */
    private Callable<V> callable;
    /** 用來存儲任務執行結果或者異常對象,根據任務state在get時候選擇返回執行結果仍是拋出異常 */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** 當前運行Run方法的線程 */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

    /** * Returns result or throws exception for completed task. * * @param s completed state value */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

    /** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Callable}. * * @param callable the callable task * @throws NullPointerException if the callable is null */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    /** * Creates a {@code FutureTask} that will, upon running, execute the * given {@code Runnable}, and arrange that {@code get} will return the * given result on successful completion. * * @param runnable the runnable task * @param result the result to return on successful completion. If * you don't need a particular result, consider using * constructions of the form: * {@code Future<?> f = new FutureTask<Void>(runnable, null)} * @throws NullPointerException if the runnable is null */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
    //判斷任務是否已取消(異常中斷、取消等)
    public boolean isCancelled() {
        return state >= CANCELLED;
    }
   /** 判斷任務是否已結束(取消、異常、完成、NORMAL都等於結束) ** public boolean isDone() { return state != NEW; } /** mayInterruptIfRunning用來決定任務的狀態。 true : 任務狀態= INTERRUPTING = 5。若是任務已經運行,則強行中斷。若是任務未運行,那麼則不會再運行 false:CANCELLED = 4。若是任務已經運行,則容許運行完成(但不能經過get獲取結果)。若是任務未運行,那麼則不會再運行 **/
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

    /** * @throws CancellationException {@inheritDoc} */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //若是任務未完全完成,那麼則阻塞直至任務完成後喚醒該線程
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

    /** * @throws CancellationException {@inheritDoc} */
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

    /** * Protected method invoked when this task transitions to state * {@code isDone} (whether normally or via cancellation). The * default implementation does nothing. Subclasses may override * this method to invoke completion callbacks or perform * bookkeeping. Note that you can query status inside the * implementation of this method to determine whether this task * has been cancelled. */
    protected void done() { }


    /** 該方法在FutureTask裏只有run方法在任務完成後調用。 主要保存任務執行結果到成員變量outcome 中,和切換任務執行狀態。 由該方法能夠得知: COMPLETING : 任務已執行完成(也多是異常完成),但還未設置結果到成員變量outcome中,也意味着還不能get NORMAL : 任務完全執行完成 **/
    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

    /** * Causes this future to report an {@link ExecutionException} * with the given throwable as its cause, unless this future has * already been set or has been cancelled. * * <p>This method is invoked internally by the {@link #run} method * upon failure of the computation. * * @param t the cause of failure */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

    /** 因爲實現了Runnable接口的緣故,該方法可由執行線程所調用。 **/
    public void run() {
        //只有當任務狀態=new時才被運行繼續執行
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //調用Callable的Call方法
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } 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);
        }
    }


    /** 若是該任務在執行過程當中不被取消或者異常結束,那麼該方法不記錄任務的執行結果,且不修改任務執行狀態。 因此該方法能夠重複執行N次。不過不能直接調用,由於是protected權限。 **/
    protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

    /** * Ensures that any interrupt from a possible cancel(true) is only * delivered to a task while in run or runAndReset. */
    private void handlePossibleCancellationInterrupt(int s) {
        // It is possible for our interrupter to stall before getting a
        // chance to interrupt us. Let's spin-wait patiently.
        if (s == INTERRUPTING)
            while (state == INTERRUPTING)
                Thread.yield(); // wait out pending interrupt

        // assert state == INTERRUPTED;

        // We want to clear any interrupt we may have received from
        // cancel(true). However, it is permissible to use interrupts
        // as an independent mechanism for a task to communicate with
        // its caller, and there is no way to clear only the
        // cancellation interrupt.
        //
        // Thread.interrupted();
    }

    /** * Simple linked list nodes to record waiting threads in a Treiber * stack. See other classes such as Phaser and SynchronousQueue * for more detailed explanation. */
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }


    /** 該方法在任務完成(包括異常完成、取消)後調用。刪除全部正在get獲取等待的節點且喚醒節點的線程。和調用done方法和置空callable. **/
    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
    }


    /** 阻塞等待任務執行完成(中斷、正常完成、超時) **/
    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 else的順序也是有講究的。 1.先判斷線程是否中斷,中斷則從隊列中移除(也可能該線程不存在於隊列中) 2.判斷當前任務是否執行完成,執行完成則再也不阻塞,直接返回。 3.若是任務狀態=COMPLETING,證實該任務處於已執行完成,正在切換任務執行狀態,CPU讓出片刻便可 4.q==null,則證實還未建立節點,則建立節點 5.q節點入隊 6和7.阻塞 **/

            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);
        }
    }

    /** * Tries to unlink a timed-out or interrupted wait node to avoid * accumulating garbage. Internal nodes are simply unspliced * without CAS since it is harmless if they are traversed anyway * by releasers. To avoid effects of unsplicing from already * removed nodes, the list is retraversed in case of an apparent * race. This is slow when there are a lot of nodes, but we don't * expect lists to be long enough to outweigh higher-overhead * schemes. */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
                    else if (pred != null) {
                        pred.next = s;
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long stateOffset;
    private static final long runnerOffset;
    private static final long waitersOffset;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = FutureTask.class;
            stateOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("state"));
            runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));
            waitersOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("waiters"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}
View Code

FutureTask簡單應用:

public class FutureTaskTest {

    public static void main(String[] args) {
        test();
    }

    private static void test() {
        Task task = new Task();
        FutureTask futureTask = new FutureTask(task);
//step3:將FutureTask提交給Thread執行
        Thread thread1 = new Thread(futureTask);
        thread1.setName("task thread 1");
        thread1.start();

//step4:獲取執行結果,因爲get()方法可能會阻塞當前調用線程,若是子任務執行時間不肯定,最好在子線程中獲取執行結果
        try {
            // boolean result = (boolean) futureTask.get();
            boolean result = (boolean) futureTask.get(5, TimeUnit.SECONDS);
            System.out.println("result:" + result);
        } catch (InterruptedException e) {
            System.out.println("守護線程阻塞被打斷...");
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("執行任務時出錯...");
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("執行超時...");
            futureTask.cancel(true);
            e.printStackTrace();
        } catch (CancellationException e) {
            //若是線程已經cancel了,再執行get操做會拋出這個異常
            System.out.println("future已經cancel了...");
            e.printStackTrace();
        }
    }


    private static final long SLEEP_TIME = 100;

    static class Task implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("curr threadName=" + Thread.currentThread().getName() + " i=" + i);
                    //模擬耗時操做
                    Thread.sleep(SLEEP_TIME);
                }
            } catch (InterruptedException e) {
                System.out.println(" is interrupted when calculating, will stop...");
                return false; // 注意這裏若是不return的話,線程還會繼續執行,因此任務超時後在這裏處理結果真後返回
            }
            return true;
        }
    }
}

1. 上述代碼的執行結果爲:

curr threadName=task thread 1 i=0
curr threadName=task thread 1 i=1
curr threadName=task thread 1 i=2
curr threadName=task thread 1 i=3
curr threadName=task thread 1 i=4
result:true

上述結果能夠看出,get方法爲阻塞執行,須要等到任務執行纔會有返回值。

 2. 當把SLEEP_TIME改成1500時,get方法回超時,進入timeout的異常處理分支,其結果以下。

curr threadName=task thread 1 i=0 curr threadName=task thread 1 i=1 curr threadName=task thread 1 i=2 curr threadName=task thread 1 i=3 執行超時... is interrupted when calculating, will stop... java.util.concurrent.TimeoutException at java.util.concurrent.FutureTask.get(FutureTask.java:205) at com.iflytek.drip.selflearn2.ConcurrentTest.FutureTaskTest.test(FutureTaskTest.java:30) at com.iflytek.drip.selflearn2.ConcurrentTest.FutureTaskTest.main(FutureTaskTest.java:16)

能夠看出超時後,任務並不會繼續執行,由於cancel方法傳了true。(這裏可以被cancel,是由於runable處於sleep狀態,若是是一直執行的任務則沒法被interrupt)

3. 當調用cancel傳值爲false時,執行結果以下:

curr threadName=task thread 1 i=0
curr threadName=task thread 1 i=1
curr threadName=task thread 1 i=2
curr threadName=task thread 1 i=3
執行超時...
java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at com.iflytek.drip.selflearn2.ConcurrentTest.FutureTaskTest.test(FutureTaskTest.java:30)
	at com.iflytek.drip.selflearn2.ConcurrentTest.FutureTaskTest.main(FutureTaskTest.java:16)
curr threadName=task thread 1 i=4

雖然執行了cancel,可是任務並無被中斷。

 

參考:

http://lixiaohui.iteye.com/blog/2319738

相關文章
相關標籤/搜索