FutureTask 源码分析

来源:互联网 发布:python编程入门下载 编辑:程序博客网 时间:2024/05/29 11:36

FutureTask是JDK中Future模式的标准实现,它同时实现了Runnable和Future两个接口,提供了可取消的异步计算,并且可以利用开始和取消计算的方法、查询计算是否完成的方法和获取计算结果的方法。

[java] view plain copy
print?
  1. public class FutureTask<V> implements RunnableFuture<V> {  
  2.     /** 所有的方法全部委托sync */  
  3.     private final Sync sync;  
  4.   
  5.     public FutureTask(Callable<V> callable) {  
  6.         if (callable == null)  
  7.             throw new NullPointerException();  
  8.         sync = new Sync(callable);  
  9.     }  
  10.   
  11.     public FutureTask(Runnable runnable, V result) {  
  12.         sync = new Sync(Executors.callable(runnable, result));  
  13.     }  
  14.   
  15.     public boolean isCancelled() {  
  16.         return sync.innerIsCancelled();  
  17.     }  
  18.   
  19.     public boolean isDone() {  
  20.         return sync.innerIsDone();  
  21.     }  
  22.   
  23.     public boolean cancel(boolean mayInterruptIfRunning) {  
  24.         return sync.innerCancel(mayInterruptIfRunning);  
  25.     }  
  26.   
  27.   
  28.     public V get() throws InterruptedException, ExecutionException {  
  29.         return sync.innerGet();  
  30.     }  
  31.   
  32.     public V get(long timeout, TimeUnit unit)  
  33.         throws InterruptedException, ExecutionException, TimeoutException {  
  34.         return sync.innerGet(unit.toNanos(timeout));  
  35.     }  
  36.   
  37.     protected void done() { }  
  38.   
  39.     protected void set(V v) {  
  40.         sync.innerSet(v);  
  41.     }  
  42.   
  43.     protected void setException(Throwable t) {  
  44.         sync.innerSetException(t);  
  45.     }  
  46.   
  47.     public void run() {  
  48.         sync.innerRun();  
  49.     }  
  50.   
  51.     protected boolean runAndReset() {  
  52.         return sync.innerRunAndReset();  
  53.     }  
  54.   
  55.     private final class Sync extends AbstractQueuedSynchronizer {  
  56.         private static final long serialVersionUID = -7828117401763700385L;  
  57.   
  58.         /** State value representing that task is ready to run */  
  59.         /** 代表起始状态 */  
  60.         private static final int READY     = 0;  
  61.         /** State value representing that task is running */  
  62.         /** 代表正在运行中状态 */  
  63.         private static final int RUNNING   = 1;  
  64.         /** State value representing that task ran */  
  65.         /** 代表运行完成的状态 */  
  66.         private static final int RAN       = 2;  
  67.         /** State value representing that task was cancelled */  
  68.         /** 代表被取消的状态 */  
  69.         private static final int CANCELLED = 4;  
  70.   
  71.         /** The underlying callable */  
  72.         private final Callable<V> callable;  
  73.         /** The result to return from get() */  
  74.         private V result;  
  75.         /** The exception to throw from get() */  
  76.         private Throwable exception;  
  77.   
  78.         /** 
  79.          * The thread running task. When nulled after set/cancel, this 
  80.          * indicates that the results are accessible.  Must be 
  81.          * volatile, to ensure visibility upon completion. 
  82.          */  
  83.         private volatile Thread runner;  
  84.   
  85.         Sync(Callable<V> callable) {  
  86.             this.callable = callable;  
  87.         }  
  88.   
  89.         /** 
  90.         *  判断是否完成或者是否取消 
  91.         *  传入0或者1 都返回0 说明任务没有完成 也没有取消 
  92.         */  
  93.         private boolean ranOrCancelled(int state) {  
  94.             return (state & (RAN | CANCELLED)) != 0;  
  95.         }  
  96.   
  97.         /** 
  98.          * AbstractQueuedSynchronizer的模板方法  
  99.          * 返回1可以获取锁 返回-1说明获取锁失败 
  100.          * 调用innerIsDone 返回TRUE 说明任务已经执行完毕 
  101.          * 返回FALSE 说明任务没有执行完毕 
  102.          */  
  103.         protected int tryAcquireShared(int ignore) {  
  104.             return innerIsDone() ? 1 : -1;  
  105.         }  
  106.   
  107.         /** 
  108.          * 释放锁 将执行当前任务的线程设置为null 
  109.          */  
  110.         protected boolean tryReleaseShared(int ignore) {  
  111.             runner = null;  
  112.             return true;  
  113.         }  
  114.   
  115.         //判断任务是否被取消  
  116.         boolean innerIsCancelled() {  
  117.             return getState() == CANCELLED;  
  118.         }  
  119.   
  120.         //判断任务是否完成(取消也算完成)  
  121.         boolean innerIsDone() {  
  122.             return ranOrCancelled(getState()) && runner == null;  
  123.         }  
  124.   
  125.         //获取结果  
  126.         V innerGet() throws InterruptedException, ExecutionException {  
  127.             //首先调用AbstractQueuedSynchronizer的方法,这个方法会调用子类方法tryAcquireShared 上面有讲  
  128.             //如果当前任务已经完成,那么当前线程可以向下运行,否则把当前线程加入队列阻塞.  
  129.             acquireSharedInterruptibly(0);  
  130.             //判断状态 如果取消了就抛CancellationException异常.  
  131.             if (getState() == CANCELLED)  
  132.                 throw new CancellationException();  
  133.             //如果任务执行过程中出现异常,这里包装一下抛出ExecutionException.  
  134.             if (exception != null)  
  135.                 throw new ExecutionException(exception);  
  136.             return result;  
  137.         }  
  138.   
  139.         //获取结果  
  140.         V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {  
  141.             //调用AbstractQueuedSynchronizer里的方法  
  142.             // return tryAcquireShared(arg) >= 0 ||doAcquireSharedNanos(arg, nanosTimeout);  
  143.             // 首先tryAcquireShared调用它获取锁,也就是看任务完事没,如果任务完事了就返回TRUE,那么执行逻辑同上。  
  144.             // 如果获取不到锁,那么就阻塞当前线程给定的时间,如果时间到了再次任务还没完成则抛出异常。  
  145.             if (!tryAcquireSharedNanos(0, nanosTimeout))  
  146.                 throw new TimeoutException();  
  147.             if (getState() == CANCELLED)  
  148.                 throw new CancellationException();  
  149.             if (exception != null)  
  150.                 throw new ExecutionException(exception);  
  151.             return result;  
  152.         }  
  153.   
  154.   
  155.         void innerSet(V v) {  
  156.             for (;;) {  
  157.                 int s = getState();  
  158.                 if (s == RAN)  
  159.                     return;  
  160.                 if (s == CANCELLED) {  
  161.                     // aggressively release to set runner to null,  
  162.                     // in case we are racing with a cancel request  
  163.                     // that will try to interrupt runner  
  164.                     releaseShared(0);  
  165.                     return;  
  166.                 }  
  167.                 //正常完成 设置状态为RAN  
  168.                 if (compareAndSetState(s, RAN)) {  
  169.                     result = v;  
  170.                     releaseShared(0);  
  171.                     done(); //通知子类  
  172.                     return;  
  173.                 }  
  174.             }  
  175.         }  
  176.   
  177.         void innerSetException(Throwable t) {  
  178.             for (;;) {  
  179.                 int s = getState();  
  180.                 if (s == RAN)  
  181.                     return;  
  182.                 if (s == CANCELLED) {  
  183.                     // aggressively release to set runner to null,  
  184.                     // in case we are racing with a cancel request  
  185.                     // that will try to interrupt runner  
  186.                     releaseShared(0);  
  187.                     return;  
  188.                 }  
  189.                 //设置异常  
  190.                 if (compareAndSetState(s, RAN)) {  
  191.                     exception = t;  
  192.                     releaseShared(0);  
  193.                     done();//通知子类  
  194.                     return;  
  195.                 }  
  196.             }  
  197.         }  
  198.   
  199.         //取消任务  
  200.         boolean innerCancel(boolean mayInterruptIfRunning) {  
  201.             for (;;) {  
  202.                 int s = getState();  
  203.                 //如果任务已经结束,则返回FALSE  
  204.                 if (ranOrCancelled(s))  
  205.                     return false;  
  206.                 //设置任务的状态为CANCELLED  
  207.                 if (compareAndSetState(s, CANCELLED))  
  208.                     break;  
  209.             }  
  210.             //如果参数mayInterruptIfRunning=TRUE,那么设置线程的终端状态  
  211.             if (mayInterruptIfRunning) {  
  212.                 Thread r = runner;  
  213.                 if (r != null)  
  214.                     r.interrupt();  
  215.             }  
  216.             //释放锁  
  217.             releaseShared(0);  
  218.             //调用子类方法,通知状态改变  
  219.             done();  
  220.             return true;  
  221.         }  
  222.   
  223.         void innerRun() {  
  224.             //如果任务不是初始状态则直接结束  
  225.             if (!compareAndSetState(READY, RUNNING))  
  226.                 return;  
  227.   
  228.             runner = Thread.currentThread();  
  229.             if (getState() == RUNNING) { // recheck after setting thread  
  230.                 V result;  
  231.                 try {  
  232.                     result = callable.call();  
  233.                 } catch (Throwable ex) {  
  234.                     //我们写的任务方法里如果出现异常则调用setException  
  235.                     setException(ex);  
  236.                     return;  
  237.                 }  
  238.                 //设置结果  
  239.                 set(result);  
  240.             } else {  
  241.                 //释放锁  
  242.                 releaseShared(0); // cancel  
  243.             }  
  244.         }  
  245.   
  246.         boolean innerRunAndReset() {  
  247.             if (!compareAndSetState(READY, RUNNING))  
  248.                 return false;  
  249.             try {  
  250.                 runner = Thread.currentThread();  
  251.                 if (getState() == RUNNING)  
  252.                     callable.call(); // don’t set result  
  253.                 runner = null;  
  254.                 return compareAndSetState(RUNNING, READY);  
  255.             } catch (Throwable ex) {  
  256.                 setException(ex);  
  257.                 return false;  
  258.             }  
  259.         }  
  260.     }  
  261. }  
public class FutureTask<V> implements RunnableFuture<V> {    /** 所有的方法全部委托sync */    private final Sync sync;    public FutureTask(Callable<V> callable) {        if (callable == null)            throw new NullPointerException();        sync = new Sync(callable);    }    public FutureTask(Runnable runnable, V result) {        sync = new Sync(Executors.callable(runnable, result));    }    public boolean isCancelled() {        return sync.innerIsCancelled();    }    public boolean isDone() {        return sync.innerIsDone();    }    public boolean cancel(boolean mayInterruptIfRunning) {        return sync.innerCancel(mayInterruptIfRunning);    }    public V get() throws InterruptedException, ExecutionException {        return sync.innerGet();    }    public V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException {        return sync.innerGet(unit.toNanos(timeout));    }    protected void done() { }    protected void set(V v) {        sync.innerSet(v);    }    protected void setException(Throwable t) {        sync.innerSetException(t);    }    public void run() {        sync.innerRun();    }    protected boolean runAndReset() {        return sync.innerRunAndReset();    }    private final class Sync extends AbstractQueuedSynchronizer {        private static final long serialVersionUID = -7828117401763700385L;        /** State value representing that task is ready to run */        /** 代表起始状态 */        private static final int READY     = 0;        /** State value representing that task is running */        /** 代表正在运行中状态 */        private static final int RUNNING   = 1;        /** State value representing that task ran */        /** 代表运行完成的状态 */        private static final int RAN       = 2;        /** State value representing that task was cancelled */        /** 代表被取消的状态 */        private static final int CANCELLED = 4;        /** The underlying callable */        private final Callable<V> callable;        /** The result to return from get() */        private V result;        /** The exception to throw from get() */        private Throwable exception;        /**         * The thread running task. When nulled after set/cancel, this         * indicates that the results are accessible.  Must be         * volatile, to ensure visibility upon completion.         */        private volatile Thread runner;        Sync(Callable<V> callable) {            this.callable = callable;        }        /**        *  判断是否完成或者是否取消        *  传入0或者1 都返回0 说明任务没有完成 也没有取消        */        private boolean ranOrCancelled(int state) {            return (state & (RAN | CANCELLED)) != 0;        }        /**         * AbstractQueuedSynchronizer的模板方法          * 返回1可以获取锁 返回-1说明获取锁失败         * 调用innerIsDone 返回TRUE 说明任务已经执行完毕         * 返回FALSE 说明任务没有执行完毕         */        protected int tryAcquireShared(int ignore) {            return innerIsDone() ? 1 : -1;        }        /**         * 释放锁 将执行当前任务的线程设置为null         */        protected boolean tryReleaseShared(int ignore) {            runner = null;            return true;        }        //判断任务是否被取消        boolean innerIsCancelled() {            return getState() == CANCELLED;        }        //判断任务是否完成(取消也算完成)        boolean innerIsDone() {            return ranOrCancelled(getState()) && runner == null;        }        //获取结果        V innerGet() throws InterruptedException, ExecutionException {            //首先调用AbstractQueuedSynchronizer的方法,这个方法会调用子类方法tryAcquireShared 上面有讲            //如果当前任务已经完成,那么当前线程可以向下运行,否则把当前线程加入队列阻塞.            acquireSharedInterruptibly(0);            //判断状态 如果取消了就抛CancellationException异常.            if (getState() == CANCELLED)                throw new CancellationException();            //如果任务执行过程中出现异常,这里包装一下抛出ExecutionException.            if (exception != null)                throw new ExecutionException(exception);            return result;        }        //获取结果        V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {            //调用AbstractQueuedSynchronizer里的方法            // return tryAcquireShared(arg) >= 0 ||doAcquireSharedNanos(arg, nanosTimeout);            // 首先tryAcquireShared调用它获取锁,也就是看任务完事没,如果任务完事了就返回TRUE,那么执行逻辑同上。            // 如果获取不到锁,那么就阻塞当前线程给定的时间,如果时间到了再次任务还没完成则抛出异常。            if (!tryAcquireSharedNanos(0, nanosTimeout))                throw new TimeoutException();            if (getState() == CANCELLED)                throw new CancellationException();            if (exception != null)                throw new ExecutionException(exception);            return result;        }        void innerSet(V v) {            for (;;) {                int s = getState();                if (s == RAN)                    return;                if (s == CANCELLED) {                    // aggressively release to set runner to null,                    // in case we are racing with a cancel request                    // that will try to interrupt runner                    releaseShared(0);                    return;                }                //正常完成 设置状态为RAN                if (compareAndSetState(s, RAN)) {                    result = v;                    releaseShared(0);                    done(); //通知子类                    return;                }            }        }        void innerSetException(Throwable t) {            for (;;) {                int s = getState();                if (s == RAN)                    return;                if (s == CANCELLED) {                    // aggressively release to set runner to null,                    // in case we are racing with a cancel request                    // that will try to interrupt runner                    releaseShared(0);                    return;                }                //设置异常                if (compareAndSetState(s, RAN)) {                    exception = t;                    releaseShared(0);                    done();//通知子类                    return;                }            }        }        //取消任务        boolean innerCancel(boolean mayInterruptIfRunning) {            for (;;) {                int s = getState();                //如果任务已经结束,则返回FALSE                if (ranOrCancelled(s))                    return false;                //设置任务的状态为CANCELLED                if (compareAndSetState(s, CANCELLED))                    break;            }            //如果参数mayInterruptIfRunning=TRUE,那么设置线程的终端状态            if (mayInterruptIfRunning) {                Thread r = runner;                if (r != null)                    r.interrupt();            }            //释放锁            releaseShared(0);            //调用子类方法,通知状态改变            done();            return true;        }        void innerRun() {            //如果任务不是初始状态则直接结束            if (!compareAndSetState(READY, RUNNING))                return;            runner = Thread.currentThread();            if (getState() == RUNNING) { // recheck after setting thread                V result;                try {                    result = callable.call();                } catch (Throwable ex) {                    //我们写的任务方法里如果出现异常则调用setException                    setException(ex);                    return;                }                //设置结果                set(result);            } else {                //释放锁                releaseShared(0); // cancel            }        }        boolean innerRunAndReset() {            if (!compareAndSetState(READY, RUNNING))                return false;            try {                runner = Thread.currentThread();                if (getState() == RUNNING)                    callable.call(); // don't set result                runner = null;                return compareAndSetState(RUNNING, READY);            } catch (Throwable ex) {                setException(ex);                return false;            }        }    }}


0 0
原创粉丝点击