rt/emul/compact/src/main/java/java/util/concurrent/FutureTask.java
branchjdk7-b147
changeset 1890 212417b74b72
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/util/concurrent/FutureTask.java	Sat Mar 19 10:46:31 2016 +0100
     1.3 @@ -0,0 +1,360 @@
     1.4 +/*
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.6 + *
     1.7 + * This code is free software; you can redistribute it and/or modify it
     1.8 + * under the terms of the GNU General Public License version 2 only, as
     1.9 + * published by the Free Software Foundation.  Oracle designates this
    1.10 + * particular file as subject to the "Classpath" exception as provided
    1.11 + * by Oracle in the LICENSE file that accompanied this code.
    1.12 + *
    1.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.15 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.16 + * version 2 for more details (a copy is included in the LICENSE file that
    1.17 + * accompanied this code).
    1.18 + *
    1.19 + * You should have received a copy of the GNU General Public License version
    1.20 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.22 + *
    1.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.24 + * or visit www.oracle.com if you need additional information or have any
    1.25 + * questions.
    1.26 + */
    1.27 +
    1.28 +/*
    1.29 + * This file is available under and governed by the GNU General Public
    1.30 + * License version 2 only, as published by the Free Software Foundation.
    1.31 + * However, the following notice accompanied the original version of this
    1.32 + * file:
    1.33 + *
    1.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
    1.35 + * Expert Group and released to the public domain, as explained at
    1.36 + * http://creativecommons.org/publicdomain/zero/1.0/
    1.37 + */
    1.38 +
    1.39 +package java.util.concurrent;
    1.40 +import java.util.concurrent.locks.*;
    1.41 +
    1.42 +/**
    1.43 + * A cancellable asynchronous computation.  This class provides a base
    1.44 + * implementation of {@link Future}, with methods to start and cancel
    1.45 + * a computation, query to see if the computation is complete, and
    1.46 + * retrieve the result of the computation.  The result can only be
    1.47 + * retrieved when the computation has completed; the <tt>get</tt>
    1.48 + * method will block if the computation has not yet completed.  Once
    1.49 + * the computation has completed, the computation cannot be restarted
    1.50 + * or cancelled.
    1.51 + *
    1.52 + * <p>A <tt>FutureTask</tt> can be used to wrap a {@link Callable} or
    1.53 + * {@link java.lang.Runnable} object.  Because <tt>FutureTask</tt>
    1.54 + * implements <tt>Runnable</tt>, a <tt>FutureTask</tt> can be
    1.55 + * submitted to an {@link Executor} for execution.
    1.56 + *
    1.57 + * <p>In addition to serving as a standalone class, this class provides
    1.58 + * <tt>protected</tt> functionality that may be useful when creating
    1.59 + * customized task classes.
    1.60 + *
    1.61 + * @since 1.5
    1.62 + * @author Doug Lea
    1.63 + * @param <V> The result type returned by this FutureTask's <tt>get</tt> method
    1.64 + */
    1.65 +public class FutureTask<V> implements RunnableFuture<V> {
    1.66 +    /** Synchronization control for FutureTask */
    1.67 +    private final Sync sync;
    1.68 +
    1.69 +    /**
    1.70 +     * Creates a <tt>FutureTask</tt> that will, upon running, execute the
    1.71 +     * given <tt>Callable</tt>.
    1.72 +     *
    1.73 +     * @param  callable the callable task
    1.74 +     * @throws NullPointerException if callable is null
    1.75 +     */
    1.76 +    public FutureTask(Callable<V> callable) {
    1.77 +        if (callable == null)
    1.78 +            throw new NullPointerException();
    1.79 +        sync = new Sync(callable);
    1.80 +    }
    1.81 +
    1.82 +    /**
    1.83 +     * Creates a <tt>FutureTask</tt> that will, upon running, execute the
    1.84 +     * given <tt>Runnable</tt>, and arrange that <tt>get</tt> will return the
    1.85 +     * given result on successful completion.
    1.86 +     *
    1.87 +     * @param runnable the runnable task
    1.88 +     * @param result the result to return on successful completion. If
    1.89 +     * you don't need a particular result, consider using
    1.90 +     * constructions of the form:
    1.91 +     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
    1.92 +     * @throws NullPointerException if runnable is null
    1.93 +     */
    1.94 +    public FutureTask(Runnable runnable, V result) {
    1.95 +        sync = new Sync(Executors.callable(runnable, result));
    1.96 +    }
    1.97 +
    1.98 +    public boolean isCancelled() {
    1.99 +        return sync.innerIsCancelled();
   1.100 +    }
   1.101 +
   1.102 +    public boolean isDone() {
   1.103 +        return sync.innerIsDone();
   1.104 +    }
   1.105 +
   1.106 +    public boolean cancel(boolean mayInterruptIfRunning) {
   1.107 +        return sync.innerCancel(mayInterruptIfRunning);
   1.108 +    }
   1.109 +
   1.110 +    /**
   1.111 +     * @throws CancellationException {@inheritDoc}
   1.112 +     */
   1.113 +    public V get() throws InterruptedException, ExecutionException {
   1.114 +        return sync.innerGet();
   1.115 +    }
   1.116 +
   1.117 +    /**
   1.118 +     * @throws CancellationException {@inheritDoc}
   1.119 +     */
   1.120 +    public V get(long timeout, TimeUnit unit)
   1.121 +        throws InterruptedException, ExecutionException, TimeoutException {
   1.122 +        return sync.innerGet(unit.toNanos(timeout));
   1.123 +    }
   1.124 +
   1.125 +    /**
   1.126 +     * Protected method invoked when this task transitions to state
   1.127 +     * <tt>isDone</tt> (whether normally or via cancellation). The
   1.128 +     * default implementation does nothing.  Subclasses may override
   1.129 +     * this method to invoke completion callbacks or perform
   1.130 +     * bookkeeping. Note that you can query status inside the
   1.131 +     * implementation of this method to determine whether this task
   1.132 +     * has been cancelled.
   1.133 +     */
   1.134 +    protected void done() { }
   1.135 +
   1.136 +    /**
   1.137 +     * Sets the result of this Future to the given value unless
   1.138 +     * this future has already been set or has been cancelled.
   1.139 +     * This method is invoked internally by the <tt>run</tt> method
   1.140 +     * upon successful completion of the computation.
   1.141 +     * @param v the value
   1.142 +     */
   1.143 +    protected void set(V v) {
   1.144 +        sync.innerSet(v);
   1.145 +    }
   1.146 +
   1.147 +    /**
   1.148 +     * Causes this future to report an <tt>ExecutionException</tt>
   1.149 +     * with the given throwable as its cause, unless this Future has
   1.150 +     * already been set or has been cancelled.
   1.151 +     * This method is invoked internally by the <tt>run</tt> method
   1.152 +     * upon failure of the computation.
   1.153 +     * @param t the cause of failure
   1.154 +     */
   1.155 +    protected void setException(Throwable t) {
   1.156 +        sync.innerSetException(t);
   1.157 +    }
   1.158 +
   1.159 +    // The following (duplicated) doc comment can be removed once
   1.160 +    //
   1.161 +    // 6270645: Javadoc comments should be inherited from most derived
   1.162 +    //          superinterface or superclass
   1.163 +    // is fixed.
   1.164 +    /**
   1.165 +     * Sets this Future to the result of its computation
   1.166 +     * unless it has been cancelled.
   1.167 +     */
   1.168 +    public void run() {
   1.169 +        sync.innerRun();
   1.170 +    }
   1.171 +
   1.172 +    /**
   1.173 +     * Executes the computation without setting its result, and then
   1.174 +     * resets this Future to initial state, failing to do so if the
   1.175 +     * computation encounters an exception or is cancelled.  This is
   1.176 +     * designed for use with tasks that intrinsically execute more
   1.177 +     * than once.
   1.178 +     * @return true if successfully run and reset
   1.179 +     */
   1.180 +    protected boolean runAndReset() {
   1.181 +        return sync.innerRunAndReset();
   1.182 +    }
   1.183 +
   1.184 +    /**
   1.185 +     * Synchronization control for FutureTask. Note that this must be
   1.186 +     * a non-static inner class in order to invoke the protected
   1.187 +     * <tt>done</tt> method. For clarity, all inner class support
   1.188 +     * methods are same as outer, prefixed with "inner".
   1.189 +     *
   1.190 +     * Uses AQS sync state to represent run status
   1.191 +     */
   1.192 +    private final class Sync extends AbstractQueuedSynchronizer {
   1.193 +        private static final long serialVersionUID = -7828117401763700385L;
   1.194 +
   1.195 +        /** State value representing that task is ready to run */
   1.196 +        private static final int READY     = 0;
   1.197 +        /** State value representing that task is running */
   1.198 +        private static final int RUNNING   = 1;
   1.199 +        /** State value representing that task ran */
   1.200 +        private static final int RAN       = 2;
   1.201 +        /** State value representing that task was cancelled */
   1.202 +        private static final int CANCELLED = 4;
   1.203 +
   1.204 +        /** The underlying callable */
   1.205 +        private final Callable<V> callable;
   1.206 +        /** The result to return from get() */
   1.207 +        private V result;
   1.208 +        /** The exception to throw from get() */
   1.209 +        private Throwable exception;
   1.210 +
   1.211 +        /**
   1.212 +         * The thread running task. When nulled after set/cancel, this
   1.213 +         * indicates that the results are accessible.  Must be
   1.214 +         * volatile, to ensure visibility upon completion.
   1.215 +         */
   1.216 +        private volatile Thread runner;
   1.217 +
   1.218 +        Sync(Callable<V> callable) {
   1.219 +            this.callable = callable;
   1.220 +        }
   1.221 +
   1.222 +        private boolean ranOrCancelled(int state) {
   1.223 +            return (state & (RAN | CANCELLED)) != 0;
   1.224 +        }
   1.225 +
   1.226 +        /**
   1.227 +         * Implements AQS base acquire to succeed if ran or cancelled
   1.228 +         */
   1.229 +        protected int tryAcquireShared(int ignore) {
   1.230 +            return innerIsDone() ? 1 : -1;
   1.231 +        }
   1.232 +
   1.233 +        /**
   1.234 +         * Implements AQS base release to always signal after setting
   1.235 +         * final done status by nulling runner thread.
   1.236 +         */
   1.237 +        protected boolean tryReleaseShared(int ignore) {
   1.238 +            runner = null;
   1.239 +            return true;
   1.240 +        }
   1.241 +
   1.242 +        boolean innerIsCancelled() {
   1.243 +            return getState() == CANCELLED;
   1.244 +        }
   1.245 +
   1.246 +        boolean innerIsDone() {
   1.247 +            return ranOrCancelled(getState()) && runner == null;
   1.248 +        }
   1.249 +
   1.250 +        V innerGet() throws InterruptedException, ExecutionException {
   1.251 +            acquireSharedInterruptibly(0);
   1.252 +            if (getState() == CANCELLED)
   1.253 +                throw new CancellationException();
   1.254 +            if (exception != null)
   1.255 +                throw new ExecutionException(exception);
   1.256 +            return result;
   1.257 +        }
   1.258 +
   1.259 +        V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {
   1.260 +            if (!tryAcquireSharedNanos(0, nanosTimeout))
   1.261 +                throw new TimeoutException();
   1.262 +            if (getState() == CANCELLED)
   1.263 +                throw new CancellationException();
   1.264 +            if (exception != null)
   1.265 +                throw new ExecutionException(exception);
   1.266 +            return result;
   1.267 +        }
   1.268 +
   1.269 +        void innerSet(V v) {
   1.270 +            for (;;) {
   1.271 +                int s = getState();
   1.272 +                if (s == RAN)
   1.273 +                    return;
   1.274 +                if (s == CANCELLED) {
   1.275 +                    // aggressively release to set runner to null,
   1.276 +                    // in case we are racing with a cancel request
   1.277 +                    // that will try to interrupt runner
   1.278 +                    releaseShared(0);
   1.279 +                    return;
   1.280 +                }
   1.281 +                if (compareAndSetState(s, RAN)) {
   1.282 +                    result = v;
   1.283 +                    releaseShared(0);
   1.284 +                    done();
   1.285 +                    return;
   1.286 +                }
   1.287 +            }
   1.288 +        }
   1.289 +
   1.290 +        void innerSetException(Throwable t) {
   1.291 +            for (;;) {
   1.292 +                int s = getState();
   1.293 +                if (s == RAN)
   1.294 +                    return;
   1.295 +                if (s == CANCELLED) {
   1.296 +                    // aggressively release to set runner to null,
   1.297 +                    // in case we are racing with a cancel request
   1.298 +                    // that will try to interrupt runner
   1.299 +                    releaseShared(0);
   1.300 +                    return;
   1.301 +                }
   1.302 +                if (compareAndSetState(s, RAN)) {
   1.303 +                    exception = t;
   1.304 +                    releaseShared(0);
   1.305 +                    done();
   1.306 +                    return;
   1.307 +                }
   1.308 +            }
   1.309 +        }
   1.310 +
   1.311 +        boolean innerCancel(boolean mayInterruptIfRunning) {
   1.312 +            for (;;) {
   1.313 +                int s = getState();
   1.314 +                if (ranOrCancelled(s))
   1.315 +                    return false;
   1.316 +                if (compareAndSetState(s, CANCELLED))
   1.317 +                    break;
   1.318 +            }
   1.319 +            if (mayInterruptIfRunning) {
   1.320 +                Thread r = runner;
   1.321 +                if (r != null)
   1.322 +                    r.interrupt();
   1.323 +            }
   1.324 +            releaseShared(0);
   1.325 +            done();
   1.326 +            return true;
   1.327 +        }
   1.328 +
   1.329 +        void innerRun() {
   1.330 +            if (!compareAndSetState(READY, RUNNING))
   1.331 +                return;
   1.332 +
   1.333 +            runner = Thread.currentThread();
   1.334 +            if (getState() == RUNNING) { // recheck after setting thread
   1.335 +                V result;
   1.336 +                try {
   1.337 +                    result = callable.call();
   1.338 +                } catch (Throwable ex) {
   1.339 +                    setException(ex);
   1.340 +                    return;
   1.341 +                }
   1.342 +                set(result);
   1.343 +            } else {
   1.344 +                releaseShared(0); // cancel
   1.345 +            }
   1.346 +        }
   1.347 +
   1.348 +        boolean innerRunAndReset() {
   1.349 +            if (!compareAndSetState(READY, RUNNING))
   1.350 +                return false;
   1.351 +            try {
   1.352 +                runner = Thread.currentThread();
   1.353 +                if (getState() == RUNNING)
   1.354 +                    callable.call(); // don't set result
   1.355 +                runner = null;
   1.356 +                return compareAndSetState(RUNNING, READY);
   1.357 +            } catch (Throwable ex) {
   1.358 +                setException(ex);
   1.359 +                return false;
   1.360 +            }
   1.361 +        }
   1.362 +    }
   1.363 +}