• Future接口和Callable接口以及FeatureTask详解


    类继承关系

    Callable接口

    @FunctionalInterface
    public interface Callable<V> {
        V call() throws Exception;
    }
    

    Callable接口中只有一个call()方法,和Runnable相比,该方法有返回值并允许抛出异常。
    但是这里有一个问题,进程是要通过Thread类去创建的,但是Thread的target必须是实现了Runnable接口的类对象,所以Callable对象无法直接作为Thread对象的接口;所以要想作为target,必须同时实现Runnable接口。
    Java提供了一个FutureTask类,该类实现了Runnable接口,该类的run()方法会调用Callable对象的call()方法,这样就能把Callable和Thread结合起来使用了。同时为了方便对Callable对象的操作,Java还提供了Future接口。

    Future接口

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

    FutureTask类

    public interface RunnableFuture<V> extends Runnable, Future<V> {
        void run();
    }
    
    public class FutureTask<V> implements RunnableFuture<V> {
    ...
    }
    

    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中定义了上述几种状态。

    成员变量

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

    构造函数

       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
        }
    

    FutureTask(Callable callable)

    这个构造方法比较简单,传入一个Callable对象。

    FutureTask(Runnable runnable, V result)

    先看一下Executors的callable方法:

        public static <T> Callable<T> callable(Runnable task, T result) {
            if (task == null)
                throw new NullPointerException();
            return new RunnableAdapter<T>(task, result);
        }
    

    这里只是创建RunnableAdapter对象,再看下RunnableAdapter类(是Executors的内部类):

    static final class RunnableAdapter<T> implements Callable<T> {
            final Runnable task;
            final T result;
            RunnableAdapter(Runnable task, T result) {
                this.task = task;
                this.result = result;
            }
            public T call() {
                task.run();
                return result;
            }
        }
    

    这里的RunnableAdapter也是实现了Runnable接口,并通过call()方法调用最开始传入的Runnable对象的run()方法,并且返回最开始传入的result值。
    这里实际上是将一个Runnable对象伪装成一个Callable对象,是适配器模式。

    关键的run()方法

    上代码:

    public void run() {
            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 {
                        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);
            }
        }
    

    sun.misc.Unsafe是个什么东东?可以参考这里这里

    UNSAFE.compareAndSwapObject(this, runnerOffset,
                                             null, Thread.currentThread())
    

    这行代码是什么含义呢?compareAndSwapObject可以通过反射,根据偏移量去修改对象,第一个参数表示要修改的对象,第二个表示偏移量,第三个参数用于和偏移量对应的值进行比较,第四个参数表示如果偏移量对应的值和第三个参数一样时要把偏移量设置成的值。翻译成人话就是:如果this对象的runnerOffset偏移地址的值为null,就把它设置为Thread.currentThread()。
    那再来看看runnerOffset是啥:

    runnerOffset = UNSAFE.objectFieldOffset
                    (k.getDeclaredField("runner"));
    

    对应的就是runner成员变量。
    也就是说如果状态不是NEW或者runner不是null,run方法就直接返回。
    try块中的方法就比较好理解了,就是调Callable对象的call()方法,并通过set方法设置result。

    get方法

        public V get() throws InterruptedException, ExecutionException {
            int s = state;
            if (s <= COMPLETING)
                s = awaitDone(false, 0L);
            return report(s);
        }
    

    get方法主要是调用awaitDone方法阻塞等待结果,然后根据最终状态返回结果或抛出异常。

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

    awaitDone根据当前状态直接返回或阻塞等待,代码流程不分析,主要看下几个关键的点。

        static final class WaitNode {
            volatile Thread thread;
            volatile WaitNode next;
            WaitNode() { thread = Thread.currentThread(); }
        }
    

    WaitNode就是一个链表结构,用于记录等待当前FutureTask结果的线程。
    注意,上面调用的LockSupport.park(this)和LockSupport.parkNanos(this, nanos)方法,LockSupport类是Java 6中引入的,提供了基本的线程同步原语,前面的两个调用会导致调用线程进入阻塞,直到run()方法中调用set(result)或者setException(ex)。
    看看set()方法:

        protected void set(V v) {
            if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
                outcome = v;
                UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
                finishCompletion();
            }
        }
    

    先设置state,并将结果赋给outcome,然后更新state的最终状态,接着调用finishCompletion()。

        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
        }
    

    finishCompletion()的作用就是根据waiters链表,挨个唤醒等待FutureTask执行结果的线程,唤醒操作是通过LockSupport.unpark(t)实现的。

    cancel()操作

    public boolean cancel(boolean mayInterruptIfRunning) {
            if (!(state == NEW &&
                  UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                      mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
                return false;
            try {    // in case call to interrupt throws exception
                if (mayInterruptIfRunning) {
                    try {
                        Thread t = runner;
                        if (t != null)
                            t.interrupt();
                    } finally { // final state
                        UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                    }
                }
            } finally {
                finishCompletion();
            }
            return true;
        }
    

    cancle()就是根据是否可中断来设置state及中断状态。

    参考文档

    JDK源码

  • 相关阅读:
    【搜索】棋盘 luogu-3956
    【动态规划】石子合并 luogu-1880
    【动态规划】合唱队形 luogu-
    【模拟】报名签到 luogu-4445
    【排序+贪心】导弹拦截 luogu-1158
    【模拟】不高兴的津津
    【模拟】选数 luogu-1037
    「JOISC2020」建筑装饰 4
    「清华集训」小 Y 和恐怖的奴隶主
    「CF708E」Student's Camp
  • 原文地址:https://www.cnblogs.com/cuimiemie/p/6445154.html
Copyright © 2020-2023  润新知