java基础:Future原理

1,767 阅读3分钟

上篇文章java基础:Future简介 介绍了Future的基本用法。这篇文章回答上篇文章的问题:主线程怎么获取在子线程执行的任务结果呢?如果任务在子线程中抛出了异常,主线程可以感知吗?

FutureTask

1.测试代码

@Test
public void testFutureTask() {
    Callable<String> callable = new Callable<String>() {
        @Override
        public String call() throws Exception {
            System.out.println("callable running");
            if (Math.random() < 0.5) {
                throw new RuntimeException("callable throw exception");
            }
            return "callable";
        }
    };

    FutureTask<String> futureTask = new FutureTask<>(callable);
    executorService.execute(futureTask);
    try {
        String res = futureTask.get();
        System.out.println("callable return: " + res);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

输出结果:

// 异常结果
callable running
java.util.concurrent.ExecutionException: java.lang.RuntimeException: callable throw exception
  at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122)
  at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191)
  at FutureTest.testFutureTask(FutureTest.java:101)
Caused by: java.lang.RuntimeException: callable throw exception
  at FutureTest$4.call(FutureTest.java:92)
  at FutureTest$4.call(FutureTest.java:87)
  at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
  at java.base/java.lang.Thread.run(Thread.java:834)

// 正常结果
callable running
callable return: callable

2.FutureTask定义

/**
 * A cancellable asynchronous computation.  This class provides a base
 * implementation of {@link Future}, with methods to start and cancel
 * a computation, query to see if the computation is complete, and
 * retrieve the result of the computation.  The result can only be
 * retrieved when the computation has completed; the {@code get}
 * methods will block if the computation has not yet completed.  Once
 * the computation has completed, the computation cannot be restarted
 * or cancelled (unless the computation is invoked using
 * {@link #runAndReset}).
 *
 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
 * {@link Runnable} object.  Because {@code FutureTask} implements
 * {@code Runnable}, a {@code FutureTask} can be submitted to an
 * {@link Executor} for execution.
 *
 * <p>In addition to serving as a standalone class, this class provides
 * {@code protected} functionality that may be useful when creating
 * customized task classes.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this FutureTask's {@code get} methods
 */
public class FutureTask<V> implements RunnableFuture<V>

FutureTask是一个可取消的异步计算任务。这个类是Future的一个实现。注释中有一句比较有意思:计算任务一旦完成,就不能再被启动或者取消,除非调用了runAndRest()方法(这是一个protected方法)。

3.FutureTask的run方法

public void run() {
    if (state != NEW ||
        !RUNNER.compareAndSet(this, null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                // 执行自定义Callable的call方法,并将结果放在result中
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                // 自定义Callable的call方法抛出了异常
                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);
    }
}

/**
 * Sets the result of this future to the given value unless
 * this future has already been set or has been cancelled.
 *
 * <p>This method is invoked internally by the {@link #run} method
 * upon successful completion of the computation.
 *
 * @param v the value
 */
protected void set(V v) {
    if (STATE.compareAndSet(this, NEW, COMPLETING)) {
        // 这个outcome就是FutureTask最后返回的结果
        outcome = v;
        // 设置为NORMAL状态。很重要,因为异常的时候outcome的值是具体的Throwable对象
        STATE.setRelease(this, 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 (STATE.compareAndSet(this, NEW, COMPLETING)) {
        // 异常也被赋值给了outcome
        outcome = t;
        // 设置为EXCEPTIONAL状态。
        STATE.setRelease(this, EXCEPTIONAL); // final state
        finishCompletion();
    }
}

/**
 * @throws CancellationException {@inheritDoc}
 */
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    // 如果任务还没有执行完,就等待
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

/**
 * 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;
    // 只有NORMAL状态才正常返回
    if (s == NORMAL)
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    // 异常时抛出异常
    throw new ExecutionException((Throwable)x);
}

/**
 * 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;

public boolean isCancelled() {
    return state >= CANCELLED;
}

public boolean isDone() {
    return state != NEW;
}

这个代码还是很简单的,关键位置加了注释。

其他的cancel,带有超时时间的get方法就很简单了。

二、参考

硬广告

欢迎关注公众号:double6