0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea with assistance from members of JCP JSR-166
0N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/Apackage java.util.concurrent;
6144N/Aimport java.util.concurrent.locks.LockSupport;
0N/A
0N/A/**
0N/A * A cancellable asynchronous computation. This class provides a base
0N/A * implementation of {@link Future}, with methods to start and cancel
0N/A * a computation, query to see if the computation is complete, and
0N/A * retrieve the result of the computation. The result can only be
6144N/A * retrieved when the computation has completed; the {@code get}
6144N/A * methods will block if the computation has not yet completed. Once
0N/A * the computation has completed, the computation cannot be restarted
6144N/A * or cancelled (unless the computation is invoked using
6144N/A * {@link #runAndReset}).
0N/A *
6144N/A * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
6144N/A * {@link Runnable} object. Because {@code FutureTask} implements
6144N/A * {@code Runnable}, a {@code FutureTask} can be submitted to an
6144N/A * {@link Executor} for execution.
0N/A *
0N/A * <p>In addition to serving as a standalone class, this class provides
6144N/A * {@code protected} functionality that may be useful when creating
0N/A * customized task classes.
0N/A *
0N/A * @since 1.5
0N/A * @author Doug Lea
6144N/A * @param <V> The result type returned by this FutureTask's {@code get} methods
0N/A */
0N/Apublic class FutureTask<V> implements RunnableFuture<V> {
6144N/A /*
6144N/A * Revision notes: This differs from previous versions of this
6144N/A * class that relied on AbstractQueuedSynchronizer, mainly to
6144N/A * avoid surprising users about retaining interrupt status during
6144N/A * cancellation races. Sync control in the current design relies
6144N/A * on a "state" field updated via CAS to track completion, along
6144N/A * with a simple Treiber stack to hold waiting threads.
6144N/A *
6144N/A * Style note: As usual, we bypass overhead of using
6144N/A * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics.
6144N/A */
0N/A
0N/A /**
6144N/A * The run state of this task, initially NEW. The run state
6144N/A * transitions to a terminal state only in methods set,
6144N/A * setException, and cancel. During completion, state may take on
6144N/A * transient values of COMPLETING (while outcome is being set) or
6144N/A * INTERRUPTING (only while interrupting the runner to satisfy a
6144N/A * cancel(true)). Transitions from these intermediate to final
6144N/A * states use cheaper ordered/lazy writes because values are unique
6144N/A * and cannot be further modified.
6144N/A *
6144N/A * Possible state transitions:
6144N/A * NEW -> COMPLETING -> NORMAL
6144N/A * NEW -> COMPLETING -> EXCEPTIONAL
6144N/A * NEW -> CANCELLED
6144N/A * NEW -> INTERRUPTING -> INTERRUPTED
6144N/A */
6144N/A private volatile int state;
6144N/A private static final int NEW = 0;
6144N/A private static final int COMPLETING = 1;
6144N/A private static final int NORMAL = 2;
6144N/A private static final int EXCEPTIONAL = 3;
6144N/A private static final int CANCELLED = 4;
6144N/A private static final int INTERRUPTING = 5;
6144N/A private static final int INTERRUPTED = 6;
6144N/A
6144N/A /** The underlying callable; nulled out after running */
6144N/A private Callable<V> callable;
6144N/A /** The result to return or exception to throw from get() */
6144N/A private Object outcome; // non-volatile, protected by state reads/writes
6144N/A /** The thread running the callable; CASed during run() */
6144N/A private volatile Thread runner;
6144N/A /** Treiber stack of waiting threads */
6144N/A private volatile WaitNode waiters;
6144N/A
6144N/A /**
6144N/A * Returns result or throws exception for completed task.
6144N/A *
6144N/A * @param s completed state value
6144N/A */
6144N/A @SuppressWarnings("unchecked")
6144N/A private V report(int s) throws ExecutionException {
6144N/A Object x = outcome;
6144N/A if (s == NORMAL)
6144N/A return (V)x;
6144N/A if (s >= CANCELLED)
6144N/A throw new CancellationException();
6144N/A throw new ExecutionException((Throwable)x);
6144N/A }
6144N/A
6144N/A /**
6144N/A * Creates a {@code FutureTask} that will, upon running, execute the
6144N/A * given {@code Callable}.
0N/A *
0N/A * @param callable the callable task
6144N/A * @throws NullPointerException if the callable is null
0N/A */
0N/A public FutureTask(Callable<V> callable) {
0N/A if (callable == null)
0N/A throw new NullPointerException();
6144N/A this.callable = callable;
6144N/A this.state = NEW; // ensure visibility of callable
0N/A }
0N/A
0N/A /**
6144N/A * Creates a {@code FutureTask} that will, upon running, execute the
6144N/A * given {@code Runnable}, and arrange that {@code get} will return the
0N/A * given result on successful completion.
0N/A *
0N/A * @param runnable the runnable task
0N/A * @param result the result to return on successful completion. If
0N/A * you don't need a particular result, consider using
0N/A * constructions of the form:
3203N/A * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
6144N/A * @throws NullPointerException if the runnable is null
0N/A */
0N/A public FutureTask(Runnable runnable, V result) {
6144N/A this.callable = Executors.callable(runnable, result);
6144N/A this.state = NEW; // ensure visibility of callable
0N/A }
0N/A
0N/A public boolean isCancelled() {
6144N/A return state >= CANCELLED;
0N/A }
0N/A
0N/A public boolean isDone() {
6144N/A return state != NEW;
0N/A }
0N/A
0N/A public boolean cancel(boolean mayInterruptIfRunning) {
6144N/A if (state != NEW)
6144N/A return false;
6144N/A if (mayInterruptIfRunning) {
6144N/A if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
6144N/A return false;
6144N/A Thread t = runner;
6144N/A if (t != null)
6144N/A t.interrupt();
6144N/A UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
6144N/A }
6144N/A else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
6144N/A return false;
6144N/A finishCompletion();
6144N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * @throws CancellationException {@inheritDoc}
0N/A */
0N/A public V get() throws InterruptedException, ExecutionException {
6144N/A int s = state;
6144N/A if (s <= COMPLETING)
6144N/A s = awaitDone(false, 0L);
6144N/A return report(s);
0N/A }
0N/A
0N/A /**
0N/A * @throws CancellationException {@inheritDoc}
0N/A */
0N/A public V get(long timeout, TimeUnit unit)
0N/A throws InterruptedException, ExecutionException, TimeoutException {
6144N/A if (unit == null)
6144N/A throw new NullPointerException();
6144N/A int s = state;
6144N/A if (s <= COMPLETING &&
6144N/A (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
6144N/A throw new TimeoutException();
6144N/A return report(s);
0N/A }
0N/A
0N/A /**
0N/A * Protected method invoked when this task transitions to state
6144N/A * {@code isDone} (whether normally or via cancellation). The
0N/A * default implementation does nothing. Subclasses may override
0N/A * this method to invoke completion callbacks or perform
0N/A * bookkeeping. Note that you can query status inside the
0N/A * implementation of this method to determine whether this task
0N/A * has been cancelled.
0N/A */
0N/A protected void done() { }
0N/A
0N/A /**
6144N/A * Sets the result of this future to the given value unless
0N/A * this future has already been set or has been cancelled.
6144N/A *
6144N/A * <p>This method is invoked internally by the {@link #run} method
0N/A * upon successful completion of the computation.
6144N/A *
0N/A * @param v the value
0N/A */
0N/A protected void set(V v) {
6144N/A if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
6144N/A outcome = v;
6144N/A UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
6144N/A finishCompletion();
6144N/A }
0N/A }
0N/A
0N/A /**
6144N/A * Causes this future to report an {@link ExecutionException}
6144N/A * with the given throwable as its cause, unless this future has
0N/A * already been set or has been cancelled.
6144N/A *
6144N/A * <p>This method is invoked internally by the {@link #run} method
0N/A * upon failure of the computation.
6144N/A *
0N/A * @param t the cause of failure
0N/A */
0N/A protected void setException(Throwable t) {
6144N/A if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
6144N/A outcome = t;
6144N/A UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
6144N/A finishCompletion();
6144N/A }
0N/A }
0N/A
0N/A public void run() {
6144N/A if (state != NEW ||
6144N/A !UNSAFE.compareAndSwapObject(this, runnerOffset,
6144N/A null, Thread.currentThread()))
6144N/A return;
6144N/A try {
6144N/A Callable<V> c = callable;
6144N/A if (c != null && state == NEW) {
6144N/A V result;
6144N/A boolean ran;
6144N/A try {
6144N/A result = c.call();
6144N/A ran = true;
6144N/A } catch (Throwable ex) {
6144N/A result = null;
6144N/A ran = false;
6144N/A setException(ex);
6144N/A }
6144N/A if (ran)
6144N/A set(result);
6144N/A }
6144N/A } finally {
6144N/A // runner must be non-null until state is settled to
6144N/A // prevent concurrent calls to run()
6144N/A runner = null;
6144N/A // state must be re-read after nulling runner to prevent
6144N/A // leaked interrupts
6144N/A int s = state;
6144N/A if (s >= INTERRUPTING)
6144N/A handlePossibleCancellationInterrupt(s);
6144N/A }
0N/A }
0N/A
0N/A /**
0N/A * Executes the computation without setting its result, and then
6144N/A * resets this future to initial state, failing to do so if the
0N/A * computation encounters an exception or is cancelled. This is
0N/A * designed for use with tasks that intrinsically execute more
0N/A * than once.
6144N/A *
0N/A * @return true if successfully run and reset
0N/A */
0N/A protected boolean runAndReset() {
6144N/A if (state != NEW ||
6144N/A !UNSAFE.compareAndSwapObject(this, runnerOffset,
6144N/A null, Thread.currentThread()))
6144N/A return false;
6144N/A boolean ran = false;
6144N/A int s = state;
6144N/A try {
6144N/A Callable<V> c = callable;
6144N/A if (c != null && s == NEW) {
6144N/A try {
6144N/A c.call(); // don't set result
6144N/A ran = true;
6144N/A } catch (Throwable ex) {
6144N/A setException(ex);
6144N/A }
6144N/A }
6144N/A } finally {
6144N/A // runner must be non-null until state is settled to
6144N/A // prevent concurrent calls to run()
6144N/A runner = null;
6144N/A // state must be re-read after nulling runner to prevent
6144N/A // leaked interrupts
6144N/A s = state;
6144N/A if (s >= INTERRUPTING)
6144N/A handlePossibleCancellationInterrupt(s);
6144N/A }
6144N/A return ran && s == NEW;
6144N/A }
6144N/A
6144N/A /**
6144N/A * Ensures that any interrupt from a possible cancel(true) is only
6144N/A * delivered to a task while in run or runAndReset.
6144N/A */
6144N/A private void handlePossibleCancellationInterrupt(int s) {
6144N/A // It is possible for our interrupter to stall before getting a
6144N/A // chance to interrupt us. Let's spin-wait patiently.
6144N/A if (s == INTERRUPTING)
6144N/A while (state == INTERRUPTING)
6144N/A Thread.yield(); // wait out pending interrupt
6144N/A
6144N/A // assert state == INTERRUPTED;
6144N/A
6144N/A // We want to clear any interrupt we may have received from
6144N/A // cancel(true). However, it is permissible to use interrupts
6144N/A // as an independent mechanism for a task to communicate with
6144N/A // its caller, and there is no way to clear only the
6144N/A // cancellation interrupt.
6144N/A //
6144N/A // Thread.interrupted();
6144N/A }
6144N/A
6144N/A /**
6144N/A * Simple linked list nodes to record waiting threads in a Treiber
6144N/A * stack. See other classes such as Phaser and SynchronousQueue
6144N/A * for more detailed explanation.
6144N/A */
6144N/A static final class WaitNode {
6144N/A volatile Thread thread;
6144N/A volatile WaitNode next;
6144N/A WaitNode() { thread = Thread.currentThread(); }
0N/A }
0N/A
0N/A /**
6144N/A * Removes and signals all waiting threads, invokes done(), and
6144N/A * nulls out callable.
0N/A */
6144N/A private void finishCompletion() {
6144N/A // assert state > COMPLETING;
6144N/A for (WaitNode q; (q = waiters) != null;) {
6144N/A if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
6144N/A for (;;) {
6144N/A Thread t = q.thread;
6144N/A if (t != null) {
6144N/A q.thread = null;
6144N/A LockSupport.unpark(t);
6144N/A }
6144N/A WaitNode next = q.next;
6144N/A if (next == null)
6144N/A break;
6144N/A q.next = null; // unlink to help gc
6144N/A q = next;
0N/A }
6144N/A break;
0N/A }
0N/A }
0N/A
6144N/A done();
6144N/A
6144N/A callable = null; // to reduce footprint
6144N/A }
6144N/A
6144N/A /**
6144N/A * Awaits completion or aborts on interrupt or timeout.
6144N/A *
6144N/A * @param timed true if use timed waits
6144N/A * @param nanos time to wait, if timed
6144N/A * @return state upon completion
6144N/A */
6144N/A private int awaitDone(boolean timed, long nanos)
6144N/A throws InterruptedException {
6144N/A final long deadline = timed ? System.nanoTime() + nanos : 0L;
6144N/A WaitNode q = null;
6144N/A boolean queued = false;
6144N/A for (;;) {
6144N/A if (Thread.interrupted()) {
6144N/A removeWaiter(q);
6144N/A throw new InterruptedException();
0N/A }
0N/A
6144N/A int s = state;
6144N/A if (s > COMPLETING) {
6144N/A if (q != null)
6144N/A q.thread = null;
6144N/A return s;
0N/A }
6144N/A else if (s == COMPLETING) // cannot time out yet
6144N/A Thread.yield();
6144N/A else if (q == null)
6144N/A q = new WaitNode();
6144N/A else if (!queued)
6144N/A queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
6144N/A q.next = waiters, q);
6144N/A else if (timed) {
6144N/A nanos = deadline - System.nanoTime();
6144N/A if (nanos <= 0L) {
6144N/A removeWaiter(q);
6144N/A return state;
0N/A }
6144N/A LockSupport.parkNanos(this, nanos);
0N/A }
6144N/A else
6144N/A LockSupport.park(this);
0N/A }
6144N/A }
0N/A
6144N/A /**
6144N/A * Tries to unlink a timed-out or interrupted wait node to avoid
6144N/A * accumulating garbage. Internal nodes are simply unspliced
6144N/A * without CAS since it is harmless if they are traversed anyway
6144N/A * by releasers. To avoid effects of unsplicing from already
6144N/A * removed nodes, the list is retraversed in case of an apparent
6144N/A * race. This is slow when there are a lot of nodes, but we don't
6144N/A * expect lists to be long enough to outweigh higher-overhead
6144N/A * schemes.
6144N/A */
6144N/A private void removeWaiter(WaitNode node) {
6144N/A if (node != null) {
6144N/A node.thread = null;
6144N/A retry:
6144N/A for (;;) { // restart on removeWaiter race
6144N/A for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
6144N/A s = q.next;
6144N/A if (q.thread != null)
6144N/A pred = q;
6144N/A else if (pred != null) {
6144N/A pred.next = s;
6144N/A if (pred.thread == null) // check for race
6144N/A continue retry;
6144N/A }
6144N/A else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
6144N/A q, s))
6144N/A continue retry;
6144N/A }
6144N/A break;
0N/A }
0N/A }
0N/A }
6144N/A
6144N/A // Unsafe mechanics
6144N/A private static final sun.misc.Unsafe UNSAFE;
6144N/A private static final long stateOffset;
6144N/A private static final long runnerOffset;
6144N/A private static final long waitersOffset;
6144N/A static {
6144N/A try {
6144N/A UNSAFE = sun.misc.Unsafe.getUnsafe();
6144N/A Class<?> k = FutureTask.class;
6144N/A stateOffset = UNSAFE.objectFieldOffset
6144N/A (k.getDeclaredField("state"));
6144N/A runnerOffset = UNSAFE.objectFieldOffset
6144N/A (k.getDeclaredField("runner"));
6144N/A waitersOffset = UNSAFE.objectFieldOffset
6144N/A (k.getDeclaredField("waiters"));
6144N/A } catch (Exception e) {
6144N/A throw new Error(e);
6144N/A }
6144N/A }
6144N/A
0N/A}