FutureTask的使用与原理

2020-06-07  本文已影响0人  蜗牛不要壳

FutureTask是java中一个用来实现可取消的同步计算的类。可取消是因为这个类可以调用cancel方法取消计算(其实也是有条件的取消),同步是因为调用get方法获取计算结果的时候需要等待计算完成。

1.简单使用
Callable<Integer> callable = new Callable<Integer>()
{
    @Override
    public Integer call() throws Exception
    {
        int sum = 0;
        int value = 10;
        while (value-- >= 0)
        {
            sum += value;
            try
            {
                Thread.sleep(500);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println("done");
        return sum;
    }
};


FutureTask<Integer> task = new FutureTask<Integer>(callable);
new Thread(task).start();
try
{
    System.out.println(task.get());
}
catch (InterruptedException e)
{
    e.printStackTrace();
}
catch (ExecutionException e)
{
    e.printStackTrace();
}

FutureTask的使用比较简单,通过构造方法传入Callable对象或者是Runnable对象和返回值,新开一个线程执行这个Callable对象,最后通过get方法获取计算结果。

2.原理

从FutureTask的继承关系上来看,FutureTask实现了RunnableFuture接口,RunnbleFuture接口又继承了Runnable和Future接口,所以FutureTask可以看做是一个Runnable和Future的组合体。

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

从构造方法上看,仅仅是设置了两个成员变量。当放到线程中去执行的时候,看看run方法。

public void run()
{
  //1.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
            {  
             //2.执行call的内容
                result = c.call();
                ran = true;
            }
            catch (Throwable ex)
            {
                result = null;
                ran = false;
                setException(ex);
            }
           //3.设置执行结果
            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);
    }
}

代码比较简单,首先通过CAS的方式设置runner变量为当前的线程,然后执行callable中的call方法,执行完成之后调用set方法,并且在fianlly中重置runner为null。再看下set方法。

protected void set(V v)
{
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING))
    {
        outcome = v;
        UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final 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
}

set方法中,首先通过CAS的方式设置state为Completing,然后将结果设置给outcome,在此通过CAS将state设置为NORMAL.finishCompletion方法是将通过调用get方法而导致阻塞的线程唤醒。

调用get方法的时候会同步等待,看看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的时机,如果是在COMPLETING状态之后,直接调用report方法返回。如果是在任务完成之前,则会调用awaitDone方法。awaitDone方法采用一个自旋的方式来确定state的状态,调用步奏如下:

当当前的任务执行完成之后,也就是调用set方法之后,state状态被重置,并且通过finishCompletion方法唤醒通过get方法而阻塞的线程,此时get方法继续执行,执行report方法。

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

report方法直接将set方法中设置的outcome返回即可。

再来看下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;
}

调用cancel的时机决定了它的行为,如果调用的时候,任务还没有结束,首先通过CAS的方式设置state的状态为INTERRUPTING或者是CANCELLED,然后通过finishCompletion方法唤醒所有挂起的线程,那么在上面介绍的awaitDone方法将会跳出循环,进入report方法,抛出异常。如果任务已经结束,那么cancel方法直接返回false,表示cancel失败。所有cancel方法只是取消所有get方法的挂起,立刻返回当前的值或者抛出异常,而不是关闭当前的正在运行的线程。

上一篇下一篇

猜你喜欢

热点阅读