FutureTask源码分析

1.使用场景

1.1 执行多任务计算

利用FutureTask和ExecutorService,可以用多线程的方式提交计算任务

import java.util.ArrayList;  
import java.util.List;  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.FutureTask;  

public class FutureTaskForMultiCompute {  

    public static void main(String[] args) {  

        FutureTaskForMultiCompute inst=new FutureTaskForMultiCompute();  
        // 创建任务集合  
        List<FutureTask<Integer>> taskList = new ArrayList<FutureTask<Integer>>();  
        // 创建线程池  
        ExecutorService exec = Executors.newFixedThreadPool(5);  
        for (int i = 0; i < 10; i++) {  
            // 传入Callable对象创建FutureTask对象  
            FutureTask<Integer> ft = new FutureTask<Integer>(inst.new ComputeTask(i, ""+i));  
            taskList.add(ft);  
            // 提交给线程池执行任务,也可以通过exec.invokeAll(taskList)一次性提交所有任务;  
            exec.submit(ft);  
        }  

        System.out.println("所有计算任务提交完毕, 主线程接着干其他事情!");  

        // 开始统计各计算线程计算结果  
        Integer totalResult = 0;  
        for (FutureTask<Integer> ft : taskList) {  
            try {  
                //FutureTask的get方法会自动阻塞,直到获取计算结果为止  
                totalResult = totalResult + ft.get();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            } catch (ExecutionException e) {  
                e.printStackTrace();  
            }  
        }  

        // 关闭线程池  
        exec.shutdown();  
        System.out.println("多任务计算后的总结果是:" + totalResult);  

    }  

    private class ComputeTask implements Callable<Integer> {  

        private Integer result = 0;  
        private String taskName = "";  

        public ComputeTask(Integer iniResult, String taskName){  
            result = iniResult;  
            this.taskName = taskName;  
            System.out.println("生成子线程计算任务: "+taskName);  
        }  

        public String getTaskName(){  
            return this.taskName;  
        }  

        @Override  
        public Integer call() throws Exception {  
            // TODO Auto-generated method stub  

            for (int i = 0; i < 100; i++) {  
                result =+ i;  
            }  
            // 休眠5秒钟,观察主线程行为,预期的结果是主线程会继续执行,到要取得FutureTask的结果是等待直至完成。  
            Thread.sleep(5000);  
            System.out.println("子线程计算任务: "+taskName+" 执行完成!");  
            return result;  
        }  
    }  
}  

1.2 FutureTask在高并发环境下确保任务只执行一次

在很多高并发的环境下,往往我们只需要某些任务只执行一次。这种使用情景FutureTask的特性恰能胜任。举一个例子,假设有一个带key的连接池,当key存在时,即直接返回key对应的对象;当key不存在时,则创建连接

private ConcurrentHashMap<String,FutureTask<Connection>>connectionPool = new ConcurrentHashMap<String, FutureTask<Connection>>();  

public Connection getConnection(String key) throws Exception{  
    FutureTask<Connection>connectionTask=connectionPool.get(key);  
    if(connectionTask!=null){  
        return connectionTask.get();  
    }  
    else{  
        Callable<Connection> callable = new Callable<Connection>(){  
            @Override  
            public Connection call() throws Exception {  
                // TODO Auto-generated method stub  
                return createConnection();  
            }  
        };  
        FutureTask<Connection>newTask = new FutureTask<Connection>(callable);  
        connectionTask = connectionPool.putIfAbsent(key, newTask);  
        if(connectionTask==null){  
            connectionTask = newTask;  
            connectionTask.run();  
        }  
        return connectionTask.get();  
    }  
}  

//创建Connection  
private Connection createConnection(){  
    return null;  
}  

2.源码分析

2.1 多任务计算的实现

FutureTask 实现 RunnableFuture 接口,RunableFuture接口实现了Future、Runable接口。

2.2 在FutureTask中如何判断任务是否结束

通过状态值,FutureTask定义了7个状态值,任务被创建时是新建状态。7种状态的定义如下:

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;

状态之间的转移关系如下:

  • NEW -> COMPLETING -> NORMAL
  • NEW -> COMPLETING -> EXCEPTIONAL
  • NEW -> CANCELLED
  • NEW -> INTERRUPTING -> INTERRUPTED

为什么需要这么多的状态:
因为任务的完成有:正常完成和异常完成。

FutureTask的其他属性:

/** The underlying callable; nulled out after running */
private Callable<V> callable;
/**任务执行结果 */
private Object outcome; // 不是volatile类型,值被保护通过state状态
/** 运行callable的线程 */
private volatile Thread runner;
/** Treiber stack ,存放等待结果的其他线程 */
private volatile WaitNode waiters;

/*Treiber栈节点定义*/
static final class WaitNode {
    volatile Thread thread;
    volatile WaitNode next;
    WaitNode() { thread = Thread.currentThread(); }
}

2.3 阻塞方法get()实现

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

awitDone方法实现:

阻塞线程直到任务完成。(这些阻塞的线程不会执行run方法。run方法的执行只有一个线程)

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
            /*如果状态是completing,则让出cup,但不一定成功*/
            Thread.yield();
        else if (q == null)
            //栈节点为空,则创建节点
            q = new WaitNode();
        else if (!queued)
            //把当前线程放入栈顶通过cas
            //q.next=waiters;然后把q.next的值传给except值
            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);
    }
}

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被设置完成。为了防止并发调用*/
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        //因为state是volatile
        //stte必须重新读取为了防止在runner为null后中断状态被读取
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

//handlePossibleCancellationInterrupt
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();
}

set(v)方法

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

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; //取消链接帮助gc
                q = next;
            }
            break;
        }
    }

    done();

    callable = null;
}

取消方法实现

参数:mayInterruptIfRunning 表明如果任务在运行中,是否可以中断。
1. 如果任务是非new状态。直接返回false,表示此任务不能取消
2. 如果任务是new状态。参数mayInterruptIfRunning==true,则把任务的状态设置为interrupting,标记线程开始中断。并且开始中断线程。

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

猜你喜欢

转载自blog.csdn.net/ai_xiangjuan/article/details/80640287