rt/emul/compact/src/main/java/java/util/concurrent/FutureTask.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 10:46:31 +0100
branchjdk7-b147
changeset 1890 212417b74b72
permissions -rw-r--r--
Bringing in all concurrent package from JDK7-b147
jaroslav@1890
     1
/*
jaroslav@1890
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1890
     3
 *
jaroslav@1890
     4
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1890
     5
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1890
     6
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1890
     7
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1890
     8
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1890
     9
 *
jaroslav@1890
    10
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1890
    11
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1890
    12
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1890
    13
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1890
    14
 * accompanied this code).
jaroslav@1890
    15
 *
jaroslav@1890
    16
 * You should have received a copy of the GNU General Public License version
jaroslav@1890
    17
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1890
    18
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1890
    19
 *
jaroslav@1890
    20
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1890
    21
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1890
    22
 * questions.
jaroslav@1890
    23
 */
jaroslav@1890
    24
jaroslav@1890
    25
/*
jaroslav@1890
    26
 * This file is available under and governed by the GNU General Public
jaroslav@1890
    27
 * License version 2 only, as published by the Free Software Foundation.
jaroslav@1890
    28
 * However, the following notice accompanied the original version of this
jaroslav@1890
    29
 * file:
jaroslav@1890
    30
 *
jaroslav@1890
    31
 * Written by Doug Lea with assistance from members of JCP JSR-166
jaroslav@1890
    32
 * Expert Group and released to the public domain, as explained at
jaroslav@1890
    33
 * http://creativecommons.org/publicdomain/zero/1.0/
jaroslav@1890
    34
 */
jaroslav@1890
    35
jaroslav@1890
    36
package java.util.concurrent;
jaroslav@1890
    37
import java.util.concurrent.locks.*;
jaroslav@1890
    38
jaroslav@1890
    39
/**
jaroslav@1890
    40
 * A cancellable asynchronous computation.  This class provides a base
jaroslav@1890
    41
 * implementation of {@link Future}, with methods to start and cancel
jaroslav@1890
    42
 * a computation, query to see if the computation is complete, and
jaroslav@1890
    43
 * retrieve the result of the computation.  The result can only be
jaroslav@1890
    44
 * retrieved when the computation has completed; the <tt>get</tt>
jaroslav@1890
    45
 * method will block if the computation has not yet completed.  Once
jaroslav@1890
    46
 * the computation has completed, the computation cannot be restarted
jaroslav@1890
    47
 * or cancelled.
jaroslav@1890
    48
 *
jaroslav@1890
    49
 * <p>A <tt>FutureTask</tt> can be used to wrap a {@link Callable} or
jaroslav@1890
    50
 * {@link java.lang.Runnable} object.  Because <tt>FutureTask</tt>
jaroslav@1890
    51
 * implements <tt>Runnable</tt>, a <tt>FutureTask</tt> can be
jaroslav@1890
    52
 * submitted to an {@link Executor} for execution.
jaroslav@1890
    53
 *
jaroslav@1890
    54
 * <p>In addition to serving as a standalone class, this class provides
jaroslav@1890
    55
 * <tt>protected</tt> functionality that may be useful when creating
jaroslav@1890
    56
 * customized task classes.
jaroslav@1890
    57
 *
jaroslav@1890
    58
 * @since 1.5
jaroslav@1890
    59
 * @author Doug Lea
jaroslav@1890
    60
 * @param <V> The result type returned by this FutureTask's <tt>get</tt> method
jaroslav@1890
    61
 */
jaroslav@1890
    62
public class FutureTask<V> implements RunnableFuture<V> {
jaroslav@1890
    63
    /** Synchronization control for FutureTask */
jaroslav@1890
    64
    private final Sync sync;
jaroslav@1890
    65
jaroslav@1890
    66
    /**
jaroslav@1890
    67
     * Creates a <tt>FutureTask</tt> that will, upon running, execute the
jaroslav@1890
    68
     * given <tt>Callable</tt>.
jaroslav@1890
    69
     *
jaroslav@1890
    70
     * @param  callable the callable task
jaroslav@1890
    71
     * @throws NullPointerException if callable is null
jaroslav@1890
    72
     */
jaroslav@1890
    73
    public FutureTask(Callable<V> callable) {
jaroslav@1890
    74
        if (callable == null)
jaroslav@1890
    75
            throw new NullPointerException();
jaroslav@1890
    76
        sync = new Sync(callable);
jaroslav@1890
    77
    }
jaroslav@1890
    78
jaroslav@1890
    79
    /**
jaroslav@1890
    80
     * Creates a <tt>FutureTask</tt> that will, upon running, execute the
jaroslav@1890
    81
     * given <tt>Runnable</tt>, and arrange that <tt>get</tt> will return the
jaroslav@1890
    82
     * given result on successful completion.
jaroslav@1890
    83
     *
jaroslav@1890
    84
     * @param runnable the runnable task
jaroslav@1890
    85
     * @param result the result to return on successful completion. If
jaroslav@1890
    86
     * you don't need a particular result, consider using
jaroslav@1890
    87
     * constructions of the form:
jaroslav@1890
    88
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
jaroslav@1890
    89
     * @throws NullPointerException if runnable is null
jaroslav@1890
    90
     */
jaroslav@1890
    91
    public FutureTask(Runnable runnable, V result) {
jaroslav@1890
    92
        sync = new Sync(Executors.callable(runnable, result));
jaroslav@1890
    93
    }
jaroslav@1890
    94
jaroslav@1890
    95
    public boolean isCancelled() {
jaroslav@1890
    96
        return sync.innerIsCancelled();
jaroslav@1890
    97
    }
jaroslav@1890
    98
jaroslav@1890
    99
    public boolean isDone() {
jaroslav@1890
   100
        return sync.innerIsDone();
jaroslav@1890
   101
    }
jaroslav@1890
   102
jaroslav@1890
   103
    public boolean cancel(boolean mayInterruptIfRunning) {
jaroslav@1890
   104
        return sync.innerCancel(mayInterruptIfRunning);
jaroslav@1890
   105
    }
jaroslav@1890
   106
jaroslav@1890
   107
    /**
jaroslav@1890
   108
     * @throws CancellationException {@inheritDoc}
jaroslav@1890
   109
     */
jaroslav@1890
   110
    public V get() throws InterruptedException, ExecutionException {
jaroslav@1890
   111
        return sync.innerGet();
jaroslav@1890
   112
    }
jaroslav@1890
   113
jaroslav@1890
   114
    /**
jaroslav@1890
   115
     * @throws CancellationException {@inheritDoc}
jaroslav@1890
   116
     */
jaroslav@1890
   117
    public V get(long timeout, TimeUnit unit)
jaroslav@1890
   118
        throws InterruptedException, ExecutionException, TimeoutException {
jaroslav@1890
   119
        return sync.innerGet(unit.toNanos(timeout));
jaroslav@1890
   120
    }
jaroslav@1890
   121
jaroslav@1890
   122
    /**
jaroslav@1890
   123
     * Protected method invoked when this task transitions to state
jaroslav@1890
   124
     * <tt>isDone</tt> (whether normally or via cancellation). The
jaroslav@1890
   125
     * default implementation does nothing.  Subclasses may override
jaroslav@1890
   126
     * this method to invoke completion callbacks or perform
jaroslav@1890
   127
     * bookkeeping. Note that you can query status inside the
jaroslav@1890
   128
     * implementation of this method to determine whether this task
jaroslav@1890
   129
     * has been cancelled.
jaroslav@1890
   130
     */
jaroslav@1890
   131
    protected void done() { }
jaroslav@1890
   132
jaroslav@1890
   133
    /**
jaroslav@1890
   134
     * Sets the result of this Future to the given value unless
jaroslav@1890
   135
     * this future has already been set or has been cancelled.
jaroslav@1890
   136
     * This method is invoked internally by the <tt>run</tt> method
jaroslav@1890
   137
     * upon successful completion of the computation.
jaroslav@1890
   138
     * @param v the value
jaroslav@1890
   139
     */
jaroslav@1890
   140
    protected void set(V v) {
jaroslav@1890
   141
        sync.innerSet(v);
jaroslav@1890
   142
    }
jaroslav@1890
   143
jaroslav@1890
   144
    /**
jaroslav@1890
   145
     * Causes this future to report an <tt>ExecutionException</tt>
jaroslav@1890
   146
     * with the given throwable as its cause, unless this Future has
jaroslav@1890
   147
     * already been set or has been cancelled.
jaroslav@1890
   148
     * This method is invoked internally by the <tt>run</tt> method
jaroslav@1890
   149
     * upon failure of the computation.
jaroslav@1890
   150
     * @param t the cause of failure
jaroslav@1890
   151
     */
jaroslav@1890
   152
    protected void setException(Throwable t) {
jaroslav@1890
   153
        sync.innerSetException(t);
jaroslav@1890
   154
    }
jaroslav@1890
   155
jaroslav@1890
   156
    // The following (duplicated) doc comment can be removed once
jaroslav@1890
   157
    //
jaroslav@1890
   158
    // 6270645: Javadoc comments should be inherited from most derived
jaroslav@1890
   159
    //          superinterface or superclass
jaroslav@1890
   160
    // is fixed.
jaroslav@1890
   161
    /**
jaroslav@1890
   162
     * Sets this Future to the result of its computation
jaroslav@1890
   163
     * unless it has been cancelled.
jaroslav@1890
   164
     */
jaroslav@1890
   165
    public void run() {
jaroslav@1890
   166
        sync.innerRun();
jaroslav@1890
   167
    }
jaroslav@1890
   168
jaroslav@1890
   169
    /**
jaroslav@1890
   170
     * Executes the computation without setting its result, and then
jaroslav@1890
   171
     * resets this Future to initial state, failing to do so if the
jaroslav@1890
   172
     * computation encounters an exception or is cancelled.  This is
jaroslav@1890
   173
     * designed for use with tasks that intrinsically execute more
jaroslav@1890
   174
     * than once.
jaroslav@1890
   175
     * @return true if successfully run and reset
jaroslav@1890
   176
     */
jaroslav@1890
   177
    protected boolean runAndReset() {
jaroslav@1890
   178
        return sync.innerRunAndReset();
jaroslav@1890
   179
    }
jaroslav@1890
   180
jaroslav@1890
   181
    /**
jaroslav@1890
   182
     * Synchronization control for FutureTask. Note that this must be
jaroslav@1890
   183
     * a non-static inner class in order to invoke the protected
jaroslav@1890
   184
     * <tt>done</tt> method. For clarity, all inner class support
jaroslav@1890
   185
     * methods are same as outer, prefixed with "inner".
jaroslav@1890
   186
     *
jaroslav@1890
   187
     * Uses AQS sync state to represent run status
jaroslav@1890
   188
     */
jaroslav@1890
   189
    private final class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   190
        private static final long serialVersionUID = -7828117401763700385L;
jaroslav@1890
   191
jaroslav@1890
   192
        /** State value representing that task is ready to run */
jaroslav@1890
   193
        private static final int READY     = 0;
jaroslav@1890
   194
        /** State value representing that task is running */
jaroslav@1890
   195
        private static final int RUNNING   = 1;
jaroslav@1890
   196
        /** State value representing that task ran */
jaroslav@1890
   197
        private static final int RAN       = 2;
jaroslav@1890
   198
        /** State value representing that task was cancelled */
jaroslav@1890
   199
        private static final int CANCELLED = 4;
jaroslav@1890
   200
jaroslav@1890
   201
        /** The underlying callable */
jaroslav@1890
   202
        private final Callable<V> callable;
jaroslav@1890
   203
        /** The result to return from get() */
jaroslav@1890
   204
        private V result;
jaroslav@1890
   205
        /** The exception to throw from get() */
jaroslav@1890
   206
        private Throwable exception;
jaroslav@1890
   207
jaroslav@1890
   208
        /**
jaroslav@1890
   209
         * The thread running task. When nulled after set/cancel, this
jaroslav@1890
   210
         * indicates that the results are accessible.  Must be
jaroslav@1890
   211
         * volatile, to ensure visibility upon completion.
jaroslav@1890
   212
         */
jaroslav@1890
   213
        private volatile Thread runner;
jaroslav@1890
   214
jaroslav@1890
   215
        Sync(Callable<V> callable) {
jaroslav@1890
   216
            this.callable = callable;
jaroslav@1890
   217
        }
jaroslav@1890
   218
jaroslav@1890
   219
        private boolean ranOrCancelled(int state) {
jaroslav@1890
   220
            return (state & (RAN | CANCELLED)) != 0;
jaroslav@1890
   221
        }
jaroslav@1890
   222
jaroslav@1890
   223
        /**
jaroslav@1890
   224
         * Implements AQS base acquire to succeed if ran or cancelled
jaroslav@1890
   225
         */
jaroslav@1890
   226
        protected int tryAcquireShared(int ignore) {
jaroslav@1890
   227
            return innerIsDone() ? 1 : -1;
jaroslav@1890
   228
        }
jaroslav@1890
   229
jaroslav@1890
   230
        /**
jaroslav@1890
   231
         * Implements AQS base release to always signal after setting
jaroslav@1890
   232
         * final done status by nulling runner thread.
jaroslav@1890
   233
         */
jaroslav@1890
   234
        protected boolean tryReleaseShared(int ignore) {
jaroslav@1890
   235
            runner = null;
jaroslav@1890
   236
            return true;
jaroslav@1890
   237
        }
jaroslav@1890
   238
jaroslav@1890
   239
        boolean innerIsCancelled() {
jaroslav@1890
   240
            return getState() == CANCELLED;
jaroslav@1890
   241
        }
jaroslav@1890
   242
jaroslav@1890
   243
        boolean innerIsDone() {
jaroslav@1890
   244
            return ranOrCancelled(getState()) && runner == null;
jaroslav@1890
   245
        }
jaroslav@1890
   246
jaroslav@1890
   247
        V innerGet() throws InterruptedException, ExecutionException {
jaroslav@1890
   248
            acquireSharedInterruptibly(0);
jaroslav@1890
   249
            if (getState() == CANCELLED)
jaroslav@1890
   250
                throw new CancellationException();
jaroslav@1890
   251
            if (exception != null)
jaroslav@1890
   252
                throw new ExecutionException(exception);
jaroslav@1890
   253
            return result;
jaroslav@1890
   254
        }
jaroslav@1890
   255
jaroslav@1890
   256
        V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {
jaroslav@1890
   257
            if (!tryAcquireSharedNanos(0, nanosTimeout))
jaroslav@1890
   258
                throw new TimeoutException();
jaroslav@1890
   259
            if (getState() == CANCELLED)
jaroslav@1890
   260
                throw new CancellationException();
jaroslav@1890
   261
            if (exception != null)
jaroslav@1890
   262
                throw new ExecutionException(exception);
jaroslav@1890
   263
            return result;
jaroslav@1890
   264
        }
jaroslav@1890
   265
jaroslav@1890
   266
        void innerSet(V v) {
jaroslav@1890
   267
            for (;;) {
jaroslav@1890
   268
                int s = getState();
jaroslav@1890
   269
                if (s == RAN)
jaroslav@1890
   270
                    return;
jaroslav@1890
   271
                if (s == CANCELLED) {
jaroslav@1890
   272
                    // aggressively release to set runner to null,
jaroslav@1890
   273
                    // in case we are racing with a cancel request
jaroslav@1890
   274
                    // that will try to interrupt runner
jaroslav@1890
   275
                    releaseShared(0);
jaroslav@1890
   276
                    return;
jaroslav@1890
   277
                }
jaroslav@1890
   278
                if (compareAndSetState(s, RAN)) {
jaroslav@1890
   279
                    result = v;
jaroslav@1890
   280
                    releaseShared(0);
jaroslav@1890
   281
                    done();
jaroslav@1890
   282
                    return;
jaroslav@1890
   283
                }
jaroslav@1890
   284
            }
jaroslav@1890
   285
        }
jaroslav@1890
   286
jaroslav@1890
   287
        void innerSetException(Throwable t) {
jaroslav@1890
   288
            for (;;) {
jaroslav@1890
   289
                int s = getState();
jaroslav@1890
   290
                if (s == RAN)
jaroslav@1890
   291
                    return;
jaroslav@1890
   292
                if (s == CANCELLED) {
jaroslav@1890
   293
                    // aggressively release to set runner to null,
jaroslav@1890
   294
                    // in case we are racing with a cancel request
jaroslav@1890
   295
                    // that will try to interrupt runner
jaroslav@1890
   296
                    releaseShared(0);
jaroslav@1890
   297
                    return;
jaroslav@1890
   298
                }
jaroslav@1890
   299
                if (compareAndSetState(s, RAN)) {
jaroslav@1890
   300
                    exception = t;
jaroslav@1890
   301
                    releaseShared(0);
jaroslav@1890
   302
                    done();
jaroslav@1890
   303
                    return;
jaroslav@1890
   304
                }
jaroslav@1890
   305
            }
jaroslav@1890
   306
        }
jaroslav@1890
   307
jaroslav@1890
   308
        boolean innerCancel(boolean mayInterruptIfRunning) {
jaroslav@1890
   309
            for (;;) {
jaroslav@1890
   310
                int s = getState();
jaroslav@1890
   311
                if (ranOrCancelled(s))
jaroslav@1890
   312
                    return false;
jaroslav@1890
   313
                if (compareAndSetState(s, CANCELLED))
jaroslav@1890
   314
                    break;
jaroslav@1890
   315
            }
jaroslav@1890
   316
            if (mayInterruptIfRunning) {
jaroslav@1890
   317
                Thread r = runner;
jaroslav@1890
   318
                if (r != null)
jaroslav@1890
   319
                    r.interrupt();
jaroslav@1890
   320
            }
jaroslav@1890
   321
            releaseShared(0);
jaroslav@1890
   322
            done();
jaroslav@1890
   323
            return true;
jaroslav@1890
   324
        }
jaroslav@1890
   325
jaroslav@1890
   326
        void innerRun() {
jaroslav@1890
   327
            if (!compareAndSetState(READY, RUNNING))
jaroslav@1890
   328
                return;
jaroslav@1890
   329
jaroslav@1890
   330
            runner = Thread.currentThread();
jaroslav@1890
   331
            if (getState() == RUNNING) { // recheck after setting thread
jaroslav@1890
   332
                V result;
jaroslav@1890
   333
                try {
jaroslav@1890
   334
                    result = callable.call();
jaroslav@1890
   335
                } catch (Throwable ex) {
jaroslav@1890
   336
                    setException(ex);
jaroslav@1890
   337
                    return;
jaroslav@1890
   338
                }
jaroslav@1890
   339
                set(result);
jaroslav@1890
   340
            } else {
jaroslav@1890
   341
                releaseShared(0); // cancel
jaroslav@1890
   342
            }
jaroslav@1890
   343
        }
jaroslav@1890
   344
jaroslav@1890
   345
        boolean innerRunAndReset() {
jaroslav@1890
   346
            if (!compareAndSetState(READY, RUNNING))
jaroslav@1890
   347
                return false;
jaroslav@1890
   348
            try {
jaroslav@1890
   349
                runner = Thread.currentThread();
jaroslav@1890
   350
                if (getState() == RUNNING)
jaroslav@1890
   351
                    callable.call(); // don't set result
jaroslav@1890
   352
                runner = null;
jaroslav@1890
   353
                return compareAndSetState(RUNNING, READY);
jaroslav@1890
   354
            } catch (Throwable ex) {
jaroslav@1890
   355
                setException(ex);
jaroslav@1890
   356
                return false;
jaroslav@1890
   357
            }
jaroslav@1890
   358
        }
jaroslav@1890
   359
    }
jaroslav@1890
   360
}