rt/emul/compact/src/main/java/java/util/concurrent/ExecutorCompletionService.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
jaroslav@1890
    38
/**
jaroslav@1890
    39
 * A {@link CompletionService} that uses a supplied {@link Executor}
jaroslav@1890
    40
 * to execute tasks.  This class arranges that submitted tasks are,
jaroslav@1890
    41
 * upon completion, placed on a queue accessible using {@code take}.
jaroslav@1890
    42
 * The class is lightweight enough to be suitable for transient use
jaroslav@1890
    43
 * when processing groups of tasks.
jaroslav@1890
    44
 *
jaroslav@1890
    45
 * <p>
jaroslav@1890
    46
 *
jaroslav@1890
    47
 * <b>Usage Examples.</b>
jaroslav@1890
    48
 *
jaroslav@1890
    49
 * Suppose you have a set of solvers for a certain problem, each
jaroslav@1890
    50
 * returning a value of some type {@code Result}, and would like to
jaroslav@1890
    51
 * run them concurrently, processing the results of each of them that
jaroslav@1890
    52
 * return a non-null value, in some method {@code use(Result r)}. You
jaroslav@1890
    53
 * could write this as:
jaroslav@1890
    54
 *
jaroslav@1890
    55
 * <pre> {@code
jaroslav@1890
    56
 * void solve(Executor e,
jaroslav@1890
    57
 *            Collection<Callable<Result>> solvers)
jaroslav@1890
    58
 *     throws InterruptedException, ExecutionException {
jaroslav@1890
    59
 *     CompletionService<Result> ecs
jaroslav@1890
    60
 *         = new ExecutorCompletionService<Result>(e);
jaroslav@1890
    61
 *     for (Callable<Result> s : solvers)
jaroslav@1890
    62
 *         ecs.submit(s);
jaroslav@1890
    63
 *     int n = solvers.size();
jaroslav@1890
    64
 *     for (int i = 0; i < n; ++i) {
jaroslav@1890
    65
 *         Result r = ecs.take().get();
jaroslav@1890
    66
 *         if (r != null)
jaroslav@1890
    67
 *             use(r);
jaroslav@1890
    68
 *     }
jaroslav@1890
    69
 * }}</pre>
jaroslav@1890
    70
 *
jaroslav@1890
    71
 * Suppose instead that you would like to use the first non-null result
jaroslav@1890
    72
 * of the set of tasks, ignoring any that encounter exceptions,
jaroslav@1890
    73
 * and cancelling all other tasks when the first one is ready:
jaroslav@1890
    74
 *
jaroslav@1890
    75
 * <pre> {@code
jaroslav@1890
    76
 * void solve(Executor e,
jaroslav@1890
    77
 *            Collection<Callable<Result>> solvers)
jaroslav@1890
    78
 *     throws InterruptedException {
jaroslav@1890
    79
 *     CompletionService<Result> ecs
jaroslav@1890
    80
 *         = new ExecutorCompletionService<Result>(e);
jaroslav@1890
    81
 *     int n = solvers.size();
jaroslav@1890
    82
 *     List<Future<Result>> futures
jaroslav@1890
    83
 *         = new ArrayList<Future<Result>>(n);
jaroslav@1890
    84
 *     Result result = null;
jaroslav@1890
    85
 *     try {
jaroslav@1890
    86
 *         for (Callable<Result> s : solvers)
jaroslav@1890
    87
 *             futures.add(ecs.submit(s));
jaroslav@1890
    88
 *         for (int i = 0; i < n; ++i) {
jaroslav@1890
    89
 *             try {
jaroslav@1890
    90
 *                 Result r = ecs.take().get();
jaroslav@1890
    91
 *                 if (r != null) {
jaroslav@1890
    92
 *                     result = r;
jaroslav@1890
    93
 *                     break;
jaroslav@1890
    94
 *                 }
jaroslav@1890
    95
 *             } catch (ExecutionException ignore) {}
jaroslav@1890
    96
 *         }
jaroslav@1890
    97
 *     }
jaroslav@1890
    98
 *     finally {
jaroslav@1890
    99
 *         for (Future<Result> f : futures)
jaroslav@1890
   100
 *             f.cancel(true);
jaroslav@1890
   101
 *     }
jaroslav@1890
   102
 *
jaroslav@1890
   103
 *     if (result != null)
jaroslav@1890
   104
 *         use(result);
jaroslav@1890
   105
 * }}</pre>
jaroslav@1890
   106
 */
jaroslav@1890
   107
public class ExecutorCompletionService<V> implements CompletionService<V> {
jaroslav@1890
   108
    private final Executor executor;
jaroslav@1890
   109
    private final AbstractExecutorService aes;
jaroslav@1890
   110
    private final BlockingQueue<Future<V>> completionQueue;
jaroslav@1890
   111
jaroslav@1890
   112
    /**
jaroslav@1890
   113
     * FutureTask extension to enqueue upon completion
jaroslav@1890
   114
     */
jaroslav@1890
   115
    private class QueueingFuture extends FutureTask<Void> {
jaroslav@1890
   116
        QueueingFuture(RunnableFuture<V> task) {
jaroslav@1890
   117
            super(task, null);
jaroslav@1890
   118
            this.task = task;
jaroslav@1890
   119
        }
jaroslav@1890
   120
        protected void done() { completionQueue.add(task); }
jaroslav@1890
   121
        private final Future<V> task;
jaroslav@1890
   122
    }
jaroslav@1890
   123
jaroslav@1890
   124
    private RunnableFuture<V> newTaskFor(Callable<V> task) {
jaroslav@1890
   125
        if (aes == null)
jaroslav@1890
   126
            return new FutureTask<V>(task);
jaroslav@1890
   127
        else
jaroslav@1890
   128
            return aes.newTaskFor(task);
jaroslav@1890
   129
    }
jaroslav@1890
   130
jaroslav@1890
   131
    private RunnableFuture<V> newTaskFor(Runnable task, V result) {
jaroslav@1890
   132
        if (aes == null)
jaroslav@1890
   133
            return new FutureTask<V>(task, result);
jaroslav@1890
   134
        else
jaroslav@1890
   135
            return aes.newTaskFor(task, result);
jaroslav@1890
   136
    }
jaroslav@1890
   137
jaroslav@1890
   138
    /**
jaroslav@1890
   139
     * Creates an ExecutorCompletionService using the supplied
jaroslav@1890
   140
     * executor for base task execution and a
jaroslav@1890
   141
     * {@link LinkedBlockingQueue} as a completion queue.
jaroslav@1890
   142
     *
jaroslav@1890
   143
     * @param executor the executor to use
jaroslav@1890
   144
     * @throws NullPointerException if executor is {@code null}
jaroslav@1890
   145
     */
jaroslav@1890
   146
    public ExecutorCompletionService(Executor executor) {
jaroslav@1890
   147
        if (executor == null)
jaroslav@1890
   148
            throw new NullPointerException();
jaroslav@1890
   149
        this.executor = executor;
jaroslav@1890
   150
        this.aes = (executor instanceof AbstractExecutorService) ?
jaroslav@1890
   151
            (AbstractExecutorService) executor : null;
jaroslav@1890
   152
        this.completionQueue = new LinkedBlockingQueue<Future<V>>();
jaroslav@1890
   153
    }
jaroslav@1890
   154
jaroslav@1890
   155
    /**
jaroslav@1890
   156
     * Creates an ExecutorCompletionService using the supplied
jaroslav@1890
   157
     * executor for base task execution and the supplied queue as its
jaroslav@1890
   158
     * completion queue.
jaroslav@1890
   159
     *
jaroslav@1890
   160
     * @param executor the executor to use
jaroslav@1890
   161
     * @param completionQueue the queue to use as the completion queue
jaroslav@1890
   162
     *        normally one dedicated for use by this service. This
jaroslav@1890
   163
     *        queue is treated as unbounded -- failed attempted
jaroslav@1890
   164
     *        {@code Queue.add} operations for completed taskes cause
jaroslav@1890
   165
     *        them not to be retrievable.
jaroslav@1890
   166
     * @throws NullPointerException if executor or completionQueue are {@code null}
jaroslav@1890
   167
     */
jaroslav@1890
   168
    public ExecutorCompletionService(Executor executor,
jaroslav@1890
   169
                                     BlockingQueue<Future<V>> completionQueue) {
jaroslav@1890
   170
        if (executor == null || completionQueue == null)
jaroslav@1890
   171
            throw new NullPointerException();
jaroslav@1890
   172
        this.executor = executor;
jaroslav@1890
   173
        this.aes = (executor instanceof AbstractExecutorService) ?
jaroslav@1890
   174
            (AbstractExecutorService) executor : null;
jaroslav@1890
   175
        this.completionQueue = completionQueue;
jaroslav@1890
   176
    }
jaroslav@1890
   177
jaroslav@1890
   178
    public Future<V> submit(Callable<V> task) {
jaroslav@1890
   179
        if (task == null) throw new NullPointerException();
jaroslav@1890
   180
        RunnableFuture<V> f = newTaskFor(task);
jaroslav@1890
   181
        executor.execute(new QueueingFuture(f));
jaroslav@1890
   182
        return f;
jaroslav@1890
   183
    }
jaroslav@1890
   184
jaroslav@1890
   185
    public Future<V> submit(Runnable task, V result) {
jaroslav@1890
   186
        if (task == null) throw new NullPointerException();
jaroslav@1890
   187
        RunnableFuture<V> f = newTaskFor(task, result);
jaroslav@1890
   188
        executor.execute(new QueueingFuture(f));
jaroslav@1890
   189
        return f;
jaroslav@1890
   190
    }
jaroslav@1890
   191
jaroslav@1890
   192
    public Future<V> take() throws InterruptedException {
jaroslav@1890
   193
        return completionQueue.take();
jaroslav@1890
   194
    }
jaroslav@1890
   195
jaroslav@1890
   196
    public Future<V> poll() {
jaroslav@1890
   197
        return completionQueue.poll();
jaroslav@1890
   198
    }
jaroslav@1890
   199
jaroslav@1890
   200
    public Future<V> poll(long timeout, TimeUnit unit)
jaroslav@1890
   201
            throws InterruptedException {
jaroslav@1890
   202
        return completionQueue.poll(timeout, unit);
jaroslav@1890
   203
    }
jaroslav@1890
   204
jaroslav@1890
   205
}