并发十七:Future详解

Future

Future是J.U.C中的一个接口,它代表着一个异步执行结果。

Future可以看成线程在执行时留给调用者的一个存根,通过这个存在可以进行查看线程执行状态(isDone)、取消执行(cancel)、阻塞等待执行完成并返回结果(get)、异步执行回调函数(callback)等操作。

public interface Future {
    /** 取消,mayInterruptIfRunning-false:不允许在线程运行时中断 **/
    boolean cancel(boolean mayInterruptIfRunning);
    /** 是否取消**/
    boolean isCancelled();
    /** 是否完成 **/
    boolean isDone();
    /** 同步获取结果 **/
    V get() throws InterruptedException, ExecutionException;
    /** 同步获取结果,响应超时 **/
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

用ReentrantLock实现Future

一个小栗子:

public class ResponseFuture implements Future {
    private final ResponseCallback callback;
    private String responsed;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public ResponseFuture(ResponseCallback callback) {
        this.callback = callback;
    }
    public boolean isDone() {
        return null != this.responsed;
    }
    public String get() throws InterruptedException, ExecutionException {
        if (!isDone()) {
            try {
                this.lock.lock();
                while (!this.isDone()) {
                    condition.await();
                    if (this.isDone()) break;
                }
            } finally {
                this.lock.unlock();
            }
        }
        return this.responsed;
    }
    // 返回完成
    public void done(String responsed) throws Exception{
        this.responsed = responsed;
        try { 
            this.lock.lock();
            this.condition.signal();
            if(null != this.callback) this.callback.call(this.responsed);
        } finally { 
            this.lock.unlock();
        }
    }
    
    public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        throw new UnsupportedOperationException();
    }
    public boolean cancel(boolean mayInterruptIfRunning) {
        throw new UnsupportedOperationException();
    }
    public boolean isCancelled() {
        throw new UnsupportedOperationException();
    }
}

使用这个Future:

public class ResponseCallback {
    public String call(String o) {
        System.out.println("ResponseCallback:处理完成,返回:"+o);
        return o;
    }
}

public class FutureTest {
    public static void main(String[] args) {
        final ResponseFuture responseFuture = new ResponseFuture(new ResponseCallback());
        new Thread(new Runnable() {// 请求线程
            public void run() {
                System.out.println("发送一个同步请求");
                // System.out.println(responseFuture.get()); 放开这句,就是同步
                System.out.println("接着处理其他事情,过一会ResponseCallback会打印结果");
            }
        }).start();
        new Thread(new Runnable() {// 处理线程
            public void run() {
                try {
                    Thread.sleep(10000);// 模拟处理一会
                    responseFuture.done("ok");// 处理完成
                }catch (Exception e) {
                    e.printStackTrace();
                }
        
        }).start();
    }
}

这个Future使用了Condition的await和signal方法

同步操作:调用get时如果发现未有结果返回,线程阻塞等待,直到有结果返回时通知Future唤醒等待的线程。

异步操作:调用线性不用等待,有结果返回时调用signal()发现没有等待线程,直接调用Callback。

FutureTask

FutureTask是J.U.C中Future的实现,它同时也实现了Runnable接口,可以直接在ExecutorService中提交执行这个Future。

一个小栗子:

public class FutureTaskTest {

    public static class CallableImpl implements Callable{
        public String call() throws Exception {
            String tName = Thread.currentThread().getName();
            System.out.println(tName+" :开始执行");
            Thread.sleep(6000);
            return tName+" ok";
        }
    }
    public static void main(String[] args) throws Exception {
        ExecutorService es = Executors.newFixedThreadPool(1);
        
//      // 同步执行,等待6000毫秒拿到结果
//      FutureTask future = new FutureTask(new CallableImpl());
//      es.submit(future);
//      System.out.println(future.get());
        
        // 异步执行
        FutureTask future = new FutureTask(new CallableImpl()) {
            protected void done()  { 
                try {
                    System.out.println("异步返回的结果:"+this.get());
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        };
        es.submit(future);
        System.out.println("执行其他操作");

        es.shutdown();
    }

}

FutureTask实现

使用单向链表WaitNode表示排队等待的线程, volatile state表示当前线程的执行状态,状态转换如下:

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

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) //完成中
                Thread.yield();// 出让CPU
            else if (q == null)// 等待节点为空,构建节点
                q = new WaitNode();
            else if (!queued)// waiters设置为q
                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

线程执行

    // s1
    public void run() {
        // state!=NEW,说明没必要执行,返回。
        // CAS操作,将runner设置为当前线程,如果失败,说明有其他线程在执行,返回。
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable 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);// 异常 s2
                }
                if (ran)
                    set(result);// 完成 s3
            }
        } finally {
            runner = null;// 置空runner
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

s1:state不为NEW或者有其他线程在执行时,都不会执行run方法。
执行中出现异常转入s2
执行结束转入s3

    // s2
    protected void setException(Throwable t) {
        // 完成 NEW-COMPLETING-EXCEPTIONAL 状态置换
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

s2:这步完成状态:NEW-COMPLETING-EXCEPTIONAL 置换
将异常赋给结果outcome
转入s4

    // s3
    protected void set(V v) {
        // 完成NEW-COMPLETING-NORMAL状态置换
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

s3:这步完成状态:NEW-COMPLETING-NORMAL 置换
将执行结果赋给outcome
转入s4

    // s4
    private void finishCompletion() {
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {//waiters置空
                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
    }

s4:for(;;)中异常唤醒等待线程
调用回调钩子done()
被唤醒的线程会在awaitDone中让出CPU,退出循环。

小结

1、Future代表着一个异步执行结果
2、get是同步操作,当前线程会阻塞等待执行完毕,返回结果
3、异步操作使用钩子进行回调,不阻塞当前线程

你可能感兴趣的:(并发十七:Future详解)