介绍

JDK future框架,提供了一种异步编程模式,基于线程池的。将任务runnable/callable提交到线程池executor,返回一个Future对象。通过future.get()获取执行结果,这里提交到线程池,后面的操作不会阻塞。future.get()获取结果会阻塞,其实也是用多线线程执行任务。

使用

  1. future + callable
public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newSingleThreadExecutor();              
    Future<Integer> result = executorService.submit(new Callable<Integer>() {                                                                                       
        @Override                                                                       
        public Integer call() throws Exception {                                        
            TimeUnit.SECONDS.sleep(10);                                                 
            return 1;                                                                   
        }                                                                               
    });                                                                                 
    System.out.println(result.get());                                                   
}
  1. futureTask( extends Runnable, Future)
public static void main(String[] args) throws ExecutionException, InterruptedException { 
    ExecutorService executorService = Executors.newSingleThreadExecutor();               
    FutureTask task = new FutureTask(() -> {                                             
        TimeUnit.SECONDS.sleep(10);                                                      
        return 1;                                                                        
    });                                                                                  
    executorService.execute(task);                                                       
    System.out.println(task.get());                                                      
}

原理

主线程等待

在Future.get()方法内,实现了等待,哪个线程调用了某个FutureTask的get方法,就会进入到FutureTask的等待单链表里面去:WaitNode

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

任务状态

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;

直接看命名就应该知道什么意思,就不挨个说了。

  1. 某个线程调用futureTask的get方法,首先需要判断这个task是否在创建状态(NEW)或者进行中(COMPLETING),只有在创建或者进行中,才会把这个线程放入等待队列
  2. 如果不需要等待,就返回结果

工作线程会把结果放在outcome这个变量上面,report就是去这个变量上取结果并且给当前线程的,当然还需要校验任务状态

主要的逻辑就在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);                                          
    }                                                                        
}

有些代码是关于等待时间的,也就是说调用get方法的线程可以设置一定的等待时间,这里不关心

这个代码逻辑也比较简单,核心就是为了让当前线程(调用futureTask的get方法的线程)执行LockSupport.park(this);

工作线程计算结果并唤醒

线程池最终回去调用任务的run方法,所以直接看run方法的实现

public void run() {                                                    
    if (state != NEW ||                                                
        !UNSAFE.compareAndSwapObject(this, runnerOffset,               
                                     null, Thread.currentThread()))    
        return;                                                        
    try {                                                              
        Callable<V> c = callable;
        // 1
        if (c != null && state == NEW) {                               
            V result;                                                  
            boolean ran;                                               
            try {
                // 2 
                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);                    
    }                                                                  
}
  1. 判断当前任务是不是在新建状态
  2. 执行call里面的业务逻辑,并拿到结果
  3. 把第二步执行的结果放到成员变量outcome里面去,并且修改任务状态为正常结束(NORMAL)
  4. 通知所有的waiters(所有调用了当前futureTask的get方法的线程)
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; // unlink to help gc                     
                q = next;                                               
            }                                                           
            break;                                                      
        }                                                               
    }                                                                   
                                                                        
    done();                                                             
                                                                        
    callable = null;        // to reduce footprint                      
}

循环的从waiters里面拿线程,然后调用LockSupport.unpark(t),这个时候所有想要通过futureTask的get方法拿到任务的结果的线程,都被唤醒了