jdk 1.8 FutureTask

import java.util.concurrent.*;
import java.util.concurrent.locks.LockSupport;

/**
 * @author Administrator
 * @date 2018/5/26 12:23
 */
public class FutureTask<V> implements RunnableFuture<V> {

    /**
     * 可能的状态转换:
     * NEW0-> COMPLETING1-> NORMAL2     * NEW0-> COMPLETING1-> EXCEPTIONAL3     * NEW0-> CANCELLED4     * NEW0-> INTERRUPTING5-> INTERRUPTED6     */
    private volatile int state;
    //初始化的状态,表示新任务,还没有被执行
    private static final int NEW          = 0;
    //任务执行的中间态,已产生执行结果(正常返回或发生异常)而未保存
    private static final int COMPLETING   = 1;
    //任务已正常完成,执行结果已保存,状态从COMPLETING变成NORMAL,最终态
    private static final int NORMAL       = 2;
    //任务执行发生异常且异常信息已保存,状态从COMPLETING变成EXCEPTIONAL,最终态
    private static final int EXCEPTIONAL  = 3;
    //调用cancel()方法,不需要中断,任务还未执行,statenew改为CANCELLED
    private static final int CANCELLED    = 4;
    //调用取消方法,cancel(true),需要中断,state先从new改为INTERRUPTING
    private static final int INTERRUPTING = 5;
    //中断标志位被标记为truestateINTERRUPTING变为INTERRUPTED,中断的最终态
    private static final int INTERRUPTED  = 6;

    /** 执行任务的线程,执行完成置位null */
    private Callable<V> callable;
    /** get方法返回结果(正常返回或异常) */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** 执行业务处理的线程 */
    private volatile Thread runner;
    /** 等待节点 */
    private volatile WaitNode waiters;

    /**
     * 返回已完成线程的结果或异常
     *
     * @param s completed state value
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        //返回结果
        Object x = outcome;
        //线程正常完成
        if (s == NORMAL) {
            return (V)x;
        }
        //state被取消(cancel(true)发生中断),抛出CancellationException
        if (s >= CANCELLED) {
            throw new CancellationException();
        }
        //其他状态,抛出执行异常ExecutionException
        throw new ExecutionException((Throwable)x);
    }

    /**
     * 传入Callable实例,设置statenew
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null) {
            throw new NullPointerException();
        }
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * 传入Runnable实例,result为执行结果,通过Executors.callable方法将Runnable转换为成Callable     * new RunnableAdapter<T>(task, result)适配器模式,实现Callable接口,
     * call()实现中调用Runnable.run()方法,然后把传入的result作为任务的结果返回。
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * 判断任务是否被取消,如果任务在执行前被取消则返回true,否则返回false     * @return
     */
    @Override
    public boolean isCancelled() {
        //state为取消或中断时表示已取消
        return state >= CANCELLED;
    }

    /**
     * 判断任务是否已经完成,如果完成则返回true,否则返回false     * 需要注意的是:任务执行过程中发生异常、任务被取消也属于任务已完成,也会返回true     * @return
     */
    @Override
    public boolean isDone() {
        //状态不为new则表示任务已执行
        return state != NEW;
    }

    /**
     * cancel()方法用来取消异步任务的执行。如果异步任务已经完成或者已经被取消,或者由于某些原因不能取消,则会返回false     * 如果任务还没有被执行,则会返回true并且异步任务不会被执行。
     * 如果任务已经开始执行了但是还没有执行完成,若mayInterruptIfRunningtrue,则会立即中断执行任务的线程并返回true     * mayInterruptIfRunningfalse,则会返回true且不会中断任务执行线程。
     * @param mayInterruptIfRunning
     * @return
     */
    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        //任务未执行,需中断时,CASstateNEW改为INTERRUPTING;如果不需要中断,则CASstateNEW改为CANCELLED        // 任务已处理则返回false
        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
                    //修改状态为INTERRUPTED
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

    /**
     * 获取任务执行结果,如果任务还没完成则会阻塞等待直到任务执行完成。如果任务被取消则会抛出CancellationException异常,
     * 如果任务执行过程发生异常则会抛出ExecutionException异常,如果阻塞等待过程中被中断则会抛出InterruptedException异常。
     * @throws CancellationException {@inheritDoc}
     */
    @Override
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //状态<= COMPLETING表示任务没有结束,进入阻塞
        if (s <= COMPLETING) {
            s = awaitDone(false, 0L);
        }
        //任务结束,调用report返回结果
        return report(s);
    }

    /**
     * 带超时时间的get()版本,如果阻塞等待过程中超时则会抛出TimeoutException异常。
     * @throws CancellationException {@inheritDoc}
     */
    @Override
    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() { }

    /**
     * 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) {
        //CAS的把当前的状态从NEW变为COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //把执行结果保存在outcome            outcome = v;
            //CAS的把状态从COMPLETING变为NORMAL
            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) {
        //CAS的把当前的状态从NEW变为COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //把异常信息保存在outcome            outcome = t;
            //CAS的把状态从COMPLETING变为EXCEPTIONAL
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

    /**
     * 线程执行业务的方法
     */
    @Override
    public void run() {
        //如果state不是new,则说明线程已运行或者以取消;
        // 状态是new时,用CAS方法把当前线程设置为正在运行的runner,失败则返回
        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);
            }
        }
    }

    /**
     * Executes the computation without setting its result, and then
     * resets this future to initial state, failing to do so if the
     * computation encounters an exception or is cancelled.  This is
     * designed for use with tasks that intrinsically execute more
     * than once.
     *
     * @return {@code true} if successfully run and reset
     */
    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(); }
    }

    /**
     * 任务正常执行完成,异常执行完成,取消,都会调用
     *
     * 依次遍历waiters链表,唤醒节点中的线程,然后把callable置空。
     * 被唤醒的线程会各自从awaitDone()方法中的LockSupport.park*()阻塞中返回,
     * 然后会进行新一轮的循环。在新一轮的循环中会返回执行结果(或者更确切的说是返回任务的状态)     *
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     */
    private void finishCompletion() {
        // assert state > COMPLETING;
        //遍历等待队列
        for (WaitNode q; (q = waiters) != null;) {
            //waiter置位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
    }

    /**
     * Awaits completion or aborts on interrupt or timeout.
     *
     * @param timed true if use timed waits
     * @param nanos time to wait, if timed
     * @return state upon completion
     */
    private int awaitDone(boolean timed, long nanos)
            throws InterruptedException {
        //结算超时时间
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            //阻塞线程是否被中断,被中断则从等待队列中移除,并抛出InterruptedException异常
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            //任务已结束,则把thread置位null,返回结果
            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 FutureTask.WaitNode();
            } else if (!queued) {
                //如果还没有加入队列,则把当前节点插入队首,并CAS替换,替换成功则返回true,说明加入队列成功
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                        q.next = waiters, q);
            } else if (timed) {
                //剩余等待时间(超时等待通知范式)
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    //已超时,移除节点,返回state
                    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 = java.util.concurrent.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);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        /**
         * 第一种方式:Future + ExecutorService
         * CallableTask task = new CallableTask();
         * ExecutorService service = Executors.newCachedThreadPool();
         * Future<Integer> future = service.submit(task1);
         * service.shutdown();
         */


        /**
         * 第二种方式: FutureTask + ExecutorService
         * ExecutorService executor = Executors.newCachedThreadPool();
         * CallableTask task = new CallableTask();
         * FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
         * executor.submit(futureTask);
         * executor.shutdown();
         */

        /**
         * 第三种方式:FutureTask + Thread
         */

        // 2. 新建FutureTask,需要一个实现了Callable接口的类的实例作为构造函数参数
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new CallableTask());
        // 3. 新建Thread对象并启动
        Thread thread = new Thread(futureTask);
        thread.setName("CallableTask thread");
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread [" + Thread.currentThread().getName() + "] is running");

        // 4. 调用isDone()判断任务是否结束
        if(!futureTask.isDone()) {
            System.out.println("CallableTask is not done");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int result = 0;
        try {
            // 5. 调用get()方法获取任务结果,如果任务没有执行完成则阻塞等待
            result = futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("result is " + result);

    }

    // 1. 继承Callable接口,实现call()方法,泛型参数为要返回的类型
    static class CallableTask implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("Thread [" + Thread.currentThread().getName() + "] is running");
            int result = 0;
            for(int i = 0; i < 100;++i) {
                result += i;
            }

            Thread.sleep(3000);
            return result;
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值