rt/emul/compact/src/main/java/java/util/concurrent/Executors.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 12:51:03 +0100
changeset 1895 bfaf3300b7ba
parent 1890 212417b74b72
permissions -rw-r--r--
Making java.util.concurrent package compilable except ForkJoinPool
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.*;
jaroslav@1890
    38
import java.util.concurrent.atomic.AtomicInteger;
jaroslav@1890
    39
import java.security.AccessController;
jaroslav@1890
    40
import java.security.PrivilegedAction;
jaroslav@1890
    41
import java.security.PrivilegedExceptionAction;
jaroslav@1890
    42
jaroslav@1890
    43
/**
jaroslav@1890
    44
 * Factory and utility methods for {@link Executor}, {@link
jaroslav@1890
    45
 * ExecutorService}, {@link ScheduledExecutorService}, {@link
jaroslav@1890
    46
 * ThreadFactory}, and {@link Callable} classes defined in this
jaroslav@1890
    47
 * package. This class supports the following kinds of methods:
jaroslav@1890
    48
 *
jaroslav@1890
    49
 * <ul>
jaroslav@1890
    50
 *   <li> Methods that create and return an {@link ExecutorService}
jaroslav@1890
    51
 *        set up with commonly useful configuration settings.
jaroslav@1890
    52
 *   <li> Methods that create and return a {@link ScheduledExecutorService}
jaroslav@1890
    53
 *        set up with commonly useful configuration settings.
jaroslav@1890
    54
 *   <li> Methods that create and return a "wrapped" ExecutorService, that
jaroslav@1890
    55
 *        disables reconfiguration by making implementation-specific methods
jaroslav@1890
    56
 *        inaccessible.
jaroslav@1890
    57
 *   <li> Methods that create and return a {@link ThreadFactory}
jaroslav@1890
    58
 *        that sets newly created threads to a known state.
jaroslav@1890
    59
 *   <li> Methods that create and return a {@link Callable}
jaroslav@1890
    60
 *        out of other closure-like forms, so they can be used
jaroslav@1890
    61
 *        in execution methods requiring <tt>Callable</tt>.
jaroslav@1890
    62
 * </ul>
jaroslav@1890
    63
 *
jaroslav@1890
    64
 * @since 1.5
jaroslav@1890
    65
 * @author Doug Lea
jaroslav@1890
    66
 */
jaroslav@1890
    67
public class Executors {
jaroslav@1890
    68
jaroslav@1890
    69
    /**
jaroslav@1890
    70
     * Creates a thread pool that reuses a fixed number of threads
jaroslav@1890
    71
     * operating off a shared unbounded queue.  At any point, at most
jaroslav@1890
    72
     * <tt>nThreads</tt> threads will be active processing tasks.
jaroslav@1890
    73
     * If additional tasks are submitted when all threads are active,
jaroslav@1890
    74
     * they will wait in the queue until a thread is available.
jaroslav@1890
    75
     * If any thread terminates due to a failure during execution
jaroslav@1890
    76
     * prior to shutdown, a new one will take its place if needed to
jaroslav@1890
    77
     * execute subsequent tasks.  The threads in the pool will exist
jaroslav@1890
    78
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
jaroslav@1890
    79
     *
jaroslav@1890
    80
     * @param nThreads the number of threads in the pool
jaroslav@1890
    81
     * @return the newly created thread pool
jaroslav@1890
    82
     * @throws IllegalArgumentException if {@code nThreads <= 0}
jaroslav@1890
    83
     */
jaroslav@1890
    84
    public static ExecutorService newFixedThreadPool(int nThreads) {
jaroslav@1890
    85
        return new ThreadPoolExecutor(nThreads, nThreads,
jaroslav@1890
    86
                                      0L, TimeUnit.MILLISECONDS,
jaroslav@1890
    87
                                      new LinkedBlockingQueue<Runnable>());
jaroslav@1890
    88
    }
jaroslav@1890
    89
jaroslav@1890
    90
    /**
jaroslav@1890
    91
     * Creates a thread pool that reuses a fixed number of threads
jaroslav@1890
    92
     * operating off a shared unbounded queue, using the provided
jaroslav@1890
    93
     * ThreadFactory to create new threads when needed.  At any point,
jaroslav@1890
    94
     * at most <tt>nThreads</tt> threads will be active processing
jaroslav@1890
    95
     * tasks.  If additional tasks are submitted when all threads are
jaroslav@1890
    96
     * active, they will wait in the queue until a thread is
jaroslav@1890
    97
     * available.  If any thread terminates due to a failure during
jaroslav@1890
    98
     * execution prior to shutdown, a new one will take its place if
jaroslav@1890
    99
     * needed to execute subsequent tasks.  The threads in the pool will
jaroslav@1890
   100
     * exist until it is explicitly {@link ExecutorService#shutdown
jaroslav@1890
   101
     * shutdown}.
jaroslav@1890
   102
     *
jaroslav@1890
   103
     * @param nThreads the number of threads in the pool
jaroslav@1890
   104
     * @param threadFactory the factory to use when creating new threads
jaroslav@1890
   105
     * @return the newly created thread pool
jaroslav@1890
   106
     * @throws NullPointerException if threadFactory is null
jaroslav@1890
   107
     * @throws IllegalArgumentException if {@code nThreads <= 0}
jaroslav@1890
   108
     */
jaroslav@1890
   109
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
jaroslav@1890
   110
        return new ThreadPoolExecutor(nThreads, nThreads,
jaroslav@1890
   111
                                      0L, TimeUnit.MILLISECONDS,
jaroslav@1890
   112
                                      new LinkedBlockingQueue<Runnable>(),
jaroslav@1890
   113
                                      threadFactory);
jaroslav@1890
   114
    }
jaroslav@1890
   115
jaroslav@1890
   116
    /**
jaroslav@1890
   117
     * Creates an Executor that uses a single worker thread operating
jaroslav@1890
   118
     * off an unbounded queue. (Note however that if this single
jaroslav@1890
   119
     * thread terminates due to a failure during execution prior to
jaroslav@1890
   120
     * shutdown, a new one will take its place if needed to execute
jaroslav@1890
   121
     * subsequent tasks.)  Tasks are guaranteed to execute
jaroslav@1890
   122
     * sequentially, and no more than one task will be active at any
jaroslav@1890
   123
     * given time. Unlike the otherwise equivalent
jaroslav@1890
   124
     * <tt>newFixedThreadPool(1)</tt> the returned executor is
jaroslav@1890
   125
     * guaranteed not to be reconfigurable to use additional threads.
jaroslav@1890
   126
     *
jaroslav@1890
   127
     * @return the newly created single-threaded Executor
jaroslav@1890
   128
     */
jaroslav@1890
   129
    public static ExecutorService newSingleThreadExecutor() {
jaroslav@1890
   130
        return new FinalizableDelegatedExecutorService
jaroslav@1890
   131
            (new ThreadPoolExecutor(1, 1,
jaroslav@1890
   132
                                    0L, TimeUnit.MILLISECONDS,
jaroslav@1890
   133
                                    new LinkedBlockingQueue<Runnable>()));
jaroslav@1890
   134
    }
jaroslav@1890
   135
jaroslav@1890
   136
    /**
jaroslav@1890
   137
     * Creates an Executor that uses a single worker thread operating
jaroslav@1890
   138
     * off an unbounded queue, and uses the provided ThreadFactory to
jaroslav@1890
   139
     * create a new thread when needed. Unlike the otherwise
jaroslav@1890
   140
     * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the
jaroslav@1890
   141
     * returned executor is guaranteed not to be reconfigurable to use
jaroslav@1890
   142
     * additional threads.
jaroslav@1890
   143
     *
jaroslav@1890
   144
     * @param threadFactory the factory to use when creating new
jaroslav@1890
   145
     * threads
jaroslav@1890
   146
     *
jaroslav@1890
   147
     * @return the newly created single-threaded Executor
jaroslav@1890
   148
     * @throws NullPointerException if threadFactory is null
jaroslav@1890
   149
     */
jaroslav@1890
   150
    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
jaroslav@1890
   151
        return new FinalizableDelegatedExecutorService
jaroslav@1890
   152
            (new ThreadPoolExecutor(1, 1,
jaroslav@1890
   153
                                    0L, TimeUnit.MILLISECONDS,
jaroslav@1890
   154
                                    new LinkedBlockingQueue<Runnable>(),
jaroslav@1890
   155
                                    threadFactory));
jaroslav@1890
   156
    }
jaroslav@1890
   157
jaroslav@1890
   158
    /**
jaroslav@1890
   159
     * Creates a thread pool that creates new threads as needed, but
jaroslav@1890
   160
     * will reuse previously constructed threads when they are
jaroslav@1890
   161
     * available.  These pools will typically improve the performance
jaroslav@1890
   162
     * of programs that execute many short-lived asynchronous tasks.
jaroslav@1890
   163
     * Calls to <tt>execute</tt> will reuse previously constructed
jaroslav@1890
   164
     * threads if available. If no existing thread is available, a new
jaroslav@1890
   165
     * thread will be created and added to the pool. Threads that have
jaroslav@1890
   166
     * not been used for sixty seconds are terminated and removed from
jaroslav@1890
   167
     * the cache. Thus, a pool that remains idle for long enough will
jaroslav@1890
   168
     * not consume any resources. Note that pools with similar
jaroslav@1890
   169
     * properties but different details (for example, timeout parameters)
jaroslav@1890
   170
     * may be created using {@link ThreadPoolExecutor} constructors.
jaroslav@1890
   171
     *
jaroslav@1890
   172
     * @return the newly created thread pool
jaroslav@1890
   173
     */
jaroslav@1890
   174
    public static ExecutorService newCachedThreadPool() {
jaroslav@1890
   175
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
jaroslav@1890
   176
                                      60L, TimeUnit.SECONDS,
jaroslav@1890
   177
                                      new SynchronousQueue<Runnable>());
jaroslav@1890
   178
    }
jaroslav@1890
   179
jaroslav@1890
   180
    /**
jaroslav@1890
   181
     * Creates a thread pool that creates new threads as needed, but
jaroslav@1890
   182
     * will reuse previously constructed threads when they are
jaroslav@1890
   183
     * available, and uses the provided
jaroslav@1890
   184
     * ThreadFactory to create new threads when needed.
jaroslav@1890
   185
     * @param threadFactory the factory to use when creating new threads
jaroslav@1890
   186
     * @return the newly created thread pool
jaroslav@1890
   187
     * @throws NullPointerException if threadFactory is null
jaroslav@1890
   188
     */
jaroslav@1890
   189
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
jaroslav@1890
   190
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
jaroslav@1890
   191
                                      60L, TimeUnit.SECONDS,
jaroslav@1890
   192
                                      new SynchronousQueue<Runnable>(),
jaroslav@1890
   193
                                      threadFactory);
jaroslav@1890
   194
    }
jaroslav@1890
   195
jaroslav@1890
   196
    /**
jaroslav@1890
   197
     * Creates a single-threaded executor that can schedule commands
jaroslav@1890
   198
     * to run after a given delay, or to execute periodically.
jaroslav@1890
   199
     * (Note however that if this single
jaroslav@1890
   200
     * thread terminates due to a failure during execution prior to
jaroslav@1890
   201
     * shutdown, a new one will take its place if needed to execute
jaroslav@1890
   202
     * subsequent tasks.)  Tasks are guaranteed to execute
jaroslav@1890
   203
     * sequentially, and no more than one task will be active at any
jaroslav@1890
   204
     * given time. Unlike the otherwise equivalent
jaroslav@1890
   205
     * <tt>newScheduledThreadPool(1)</tt> the returned executor is
jaroslav@1890
   206
     * guaranteed not to be reconfigurable to use additional threads.
jaroslav@1890
   207
     * @return the newly created scheduled executor
jaroslav@1890
   208
     */
jaroslav@1890
   209
    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
jaroslav@1890
   210
        return new DelegatedScheduledExecutorService
jaroslav@1890
   211
            (new ScheduledThreadPoolExecutor(1));
jaroslav@1890
   212
    }
jaroslav@1890
   213
jaroslav@1890
   214
    /**
jaroslav@1890
   215
     * Creates a single-threaded executor that can schedule commands
jaroslav@1890
   216
     * to run after a given delay, or to execute periodically.  (Note
jaroslav@1890
   217
     * however that if this single thread terminates due to a failure
jaroslav@1890
   218
     * during execution prior to shutdown, a new one will take its
jaroslav@1890
   219
     * place if needed to execute subsequent tasks.)  Tasks are
jaroslav@1890
   220
     * guaranteed to execute sequentially, and no more than one task
jaroslav@1890
   221
     * will be active at any given time. Unlike the otherwise
jaroslav@1890
   222
     * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
jaroslav@1890
   223
     * the returned executor is guaranteed not to be reconfigurable to
jaroslav@1890
   224
     * use additional threads.
jaroslav@1890
   225
     * @param threadFactory the factory to use when creating new
jaroslav@1890
   226
     * threads
jaroslav@1890
   227
     * @return a newly created scheduled executor
jaroslav@1890
   228
     * @throws NullPointerException if threadFactory is null
jaroslav@1890
   229
     */
jaroslav@1890
   230
    public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
jaroslav@1890
   231
        return new DelegatedScheduledExecutorService
jaroslav@1890
   232
            (new ScheduledThreadPoolExecutor(1, threadFactory));
jaroslav@1890
   233
    }
jaroslav@1890
   234
jaroslav@1890
   235
    /**
jaroslav@1890
   236
     * Creates a thread pool that can schedule commands to run after a
jaroslav@1890
   237
     * given delay, or to execute periodically.
jaroslav@1890
   238
     * @param corePoolSize the number of threads to keep in the pool,
jaroslav@1890
   239
     * even if they are idle.
jaroslav@1890
   240
     * @return a newly created scheduled thread pool
jaroslav@1890
   241
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
jaroslav@1890
   242
     */
jaroslav@1890
   243
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
jaroslav@1890
   244
        return new ScheduledThreadPoolExecutor(corePoolSize);
jaroslav@1890
   245
    }
jaroslav@1890
   246
jaroslav@1890
   247
    /**
jaroslav@1890
   248
     * Creates a thread pool that can schedule commands to run after a
jaroslav@1890
   249
     * given delay, or to execute periodically.
jaroslav@1890
   250
     * @param corePoolSize the number of threads to keep in the pool,
jaroslav@1890
   251
     * even if they are idle.
jaroslav@1890
   252
     * @param threadFactory the factory to use when the executor
jaroslav@1890
   253
     * creates a new thread.
jaroslav@1890
   254
     * @return a newly created scheduled thread pool
jaroslav@1890
   255
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
jaroslav@1890
   256
     * @throws NullPointerException if threadFactory is null
jaroslav@1890
   257
     */
jaroslav@1890
   258
    public static ScheduledExecutorService newScheduledThreadPool(
jaroslav@1890
   259
            int corePoolSize, ThreadFactory threadFactory) {
jaroslav@1890
   260
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
jaroslav@1890
   261
    }
jaroslav@1890
   262
jaroslav@1890
   263
jaroslav@1890
   264
    /**
jaroslav@1890
   265
     * Returns an object that delegates all defined {@link
jaroslav@1890
   266
     * ExecutorService} methods to the given executor, but not any
jaroslav@1890
   267
     * other methods that might otherwise be accessible using
jaroslav@1890
   268
     * casts. This provides a way to safely "freeze" configuration and
jaroslav@1890
   269
     * disallow tuning of a given concrete implementation.
jaroslav@1890
   270
     * @param executor the underlying implementation
jaroslav@1890
   271
     * @return an <tt>ExecutorService</tt> instance
jaroslav@1890
   272
     * @throws NullPointerException if executor null
jaroslav@1890
   273
     */
jaroslav@1890
   274
    public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
jaroslav@1890
   275
        if (executor == null)
jaroslav@1890
   276
            throw new NullPointerException();
jaroslav@1890
   277
        return new DelegatedExecutorService(executor);
jaroslav@1890
   278
    }
jaroslav@1890
   279
jaroslav@1890
   280
    /**
jaroslav@1890
   281
     * Returns an object that delegates all defined {@link
jaroslav@1890
   282
     * ScheduledExecutorService} methods to the given executor, but
jaroslav@1890
   283
     * not any other methods that might otherwise be accessible using
jaroslav@1890
   284
     * casts. This provides a way to safely "freeze" configuration and
jaroslav@1890
   285
     * disallow tuning of a given concrete implementation.
jaroslav@1890
   286
     * @param executor the underlying implementation
jaroslav@1890
   287
     * @return a <tt>ScheduledExecutorService</tt> instance
jaroslav@1890
   288
     * @throws NullPointerException if executor null
jaroslav@1890
   289
     */
jaroslav@1890
   290
    public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
jaroslav@1890
   291
        if (executor == null)
jaroslav@1890
   292
            throw new NullPointerException();
jaroslav@1890
   293
        return new DelegatedScheduledExecutorService(executor);
jaroslav@1890
   294
    }
jaroslav@1890
   295
jaroslav@1890
   296
    /**
jaroslav@1890
   297
     * Returns a default thread factory used to create new threads.
jaroslav@1890
   298
     * This factory creates all new threads used by an Executor in the
jaroslav@1890
   299
     * same {@link ThreadGroup}. If there is a {@link
jaroslav@1890
   300
     * java.lang.SecurityManager}, it uses the group of {@link
jaroslav@1890
   301
     * System#getSecurityManager}, else the group of the thread
jaroslav@1890
   302
     * invoking this <tt>defaultThreadFactory</tt> method. Each new
jaroslav@1890
   303
     * thread is created as a non-daemon thread with priority set to
jaroslav@1890
   304
     * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum
jaroslav@1890
   305
     * priority permitted in the thread group.  New threads have names
jaroslav@1890
   306
     * accessible via {@link Thread#getName} of
jaroslav@1890
   307
     * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
jaroslav@1890
   308
     * number of this factory, and <em>M</em> is the sequence number
jaroslav@1890
   309
     * of the thread created by this factory.
jaroslav@1890
   310
     * @return a thread factory
jaroslav@1890
   311
     */
jaroslav@1890
   312
    public static ThreadFactory defaultThreadFactory() {
jaroslav@1890
   313
        return new DefaultThreadFactory();
jaroslav@1890
   314
    }
jaroslav@1890
   315
jaroslav@1890
   316
    /**
jaroslav@1890
   317
     * Returns a thread factory used to create new threads that
jaroslav@1890
   318
     * have the same permissions as the current thread.
jaroslav@1890
   319
     * This factory creates threads with the same settings as {@link
jaroslav@1890
   320
     * Executors#defaultThreadFactory}, additionally setting the
jaroslav@1890
   321
     * AccessControlContext and contextClassLoader of new threads to
jaroslav@1890
   322
     * be the same as the thread invoking this
jaroslav@1890
   323
     * <tt>privilegedThreadFactory</tt> method.  A new
jaroslav@1890
   324
     * <tt>privilegedThreadFactory</tt> can be created within an
jaroslav@1890
   325
     * {@link AccessController#doPrivileged} action setting the
jaroslav@1890
   326
     * current thread's access control context to create threads with
jaroslav@1890
   327
     * the selected permission settings holding within that action.
jaroslav@1890
   328
     *
jaroslav@1890
   329
     * <p> Note that while tasks running within such threads will have
jaroslav@1890
   330
     * the same access control and class loader settings as the
jaroslav@1890
   331
     * current thread, they need not have the same {@link
jaroslav@1890
   332
     * java.lang.ThreadLocal} or {@link
jaroslav@1890
   333
     * java.lang.InheritableThreadLocal} values. If necessary,
jaroslav@1890
   334
     * particular values of thread locals can be set or reset before
jaroslav@1890
   335
     * any task runs in {@link ThreadPoolExecutor} subclasses using
jaroslav@1890
   336
     * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
jaroslav@1890
   337
     * necessary to initialize worker threads to have the same
jaroslav@1890
   338
     * InheritableThreadLocal settings as some other designated
jaroslav@1890
   339
     * thread, you can create a custom ThreadFactory in which that
jaroslav@1890
   340
     * thread waits for and services requests to create others that
jaroslav@1890
   341
     * will inherit its values.
jaroslav@1890
   342
     *
jaroslav@1890
   343
     * @return a thread factory
jaroslav@1890
   344
     * @throws AccessControlException if the current access control
jaroslav@1890
   345
     * context does not have permission to both get and set context
jaroslav@1890
   346
     * class loader.
jaroslav@1890
   347
     */
jaroslav@1890
   348
    public static ThreadFactory privilegedThreadFactory() {
jaroslav@1895
   349
        throw new SecurityException();
jaroslav@1890
   350
    }
jaroslav@1890
   351
jaroslav@1890
   352
    /**
jaroslav@1890
   353
     * Returns a {@link Callable} object that, when
jaroslav@1890
   354
     * called, runs the given task and returns the given result.  This
jaroslav@1890
   355
     * can be useful when applying methods requiring a
jaroslav@1890
   356
     * <tt>Callable</tt> to an otherwise resultless action.
jaroslav@1890
   357
     * @param task the task to run
jaroslav@1890
   358
     * @param result the result to return
jaroslav@1890
   359
     * @return a callable object
jaroslav@1890
   360
     * @throws NullPointerException if task null
jaroslav@1890
   361
     */
jaroslav@1890
   362
    public static <T> Callable<T> callable(Runnable task, T result) {
jaroslav@1890
   363
        if (task == null)
jaroslav@1890
   364
            throw new NullPointerException();
jaroslav@1890
   365
        return new RunnableAdapter<T>(task, result);
jaroslav@1890
   366
    }
jaroslav@1890
   367
jaroslav@1890
   368
    /**
jaroslav@1890
   369
     * Returns a {@link Callable} object that, when
jaroslav@1890
   370
     * called, runs the given task and returns <tt>null</tt>.
jaroslav@1890
   371
     * @param task the task to run
jaroslav@1890
   372
     * @return a callable object
jaroslav@1890
   373
     * @throws NullPointerException if task null
jaroslav@1890
   374
     */
jaroslav@1890
   375
    public static Callable<Object> callable(Runnable task) {
jaroslav@1890
   376
        if (task == null)
jaroslav@1890
   377
            throw new NullPointerException();
jaroslav@1890
   378
        return new RunnableAdapter<Object>(task, null);
jaroslav@1890
   379
    }
jaroslav@1890
   380
jaroslav@1890
   381
    /**
jaroslav@1890
   382
     * Returns a {@link Callable} object that, when
jaroslav@1890
   383
     * called, runs the given privileged action and returns its result.
jaroslav@1890
   384
     * @param action the privileged action to run
jaroslav@1890
   385
     * @return a callable object
jaroslav@1890
   386
     * @throws NullPointerException if action null
jaroslav@1890
   387
     */
jaroslav@1890
   388
    public static Callable<Object> callable(final PrivilegedAction<?> action) {
jaroslav@1890
   389
        if (action == null)
jaroslav@1890
   390
            throw new NullPointerException();
jaroslav@1890
   391
        return new Callable<Object>() {
jaroslav@1890
   392
            public Object call() { return action.run(); }};
jaroslav@1890
   393
    }
jaroslav@1890
   394
jaroslav@1890
   395
    /**
jaroslav@1890
   396
     * Returns a {@link Callable} object that, when
jaroslav@1890
   397
     * called, runs the given privileged exception action and returns
jaroslav@1890
   398
     * its result.
jaroslav@1890
   399
     * @param action the privileged exception action to run
jaroslav@1890
   400
     * @return a callable object
jaroslav@1890
   401
     * @throws NullPointerException if action null
jaroslav@1890
   402
     */
jaroslav@1890
   403
    public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
jaroslav@1890
   404
        if (action == null)
jaroslav@1890
   405
            throw new NullPointerException();
jaroslav@1890
   406
        return new Callable<Object>() {
jaroslav@1890
   407
            public Object call() throws Exception { return action.run(); }};
jaroslav@1890
   408
    }
jaroslav@1890
   409
jaroslav@1890
   410
    /**
jaroslav@1890
   411
     * Returns a {@link Callable} object that will, when
jaroslav@1890
   412
     * called, execute the given <tt>callable</tt> under the current
jaroslav@1890
   413
     * access control context. This method should normally be
jaroslav@1890
   414
     * invoked within an {@link AccessController#doPrivileged} action
jaroslav@1890
   415
     * to create callables that will, if possible, execute under the
jaroslav@1890
   416
     * selected permission settings holding within that action; or if
jaroslav@1890
   417
     * not possible, throw an associated {@link
jaroslav@1890
   418
     * AccessControlException}.
jaroslav@1890
   419
     * @param callable the underlying task
jaroslav@1890
   420
     * @return a callable object
jaroslav@1890
   421
     * @throws NullPointerException if callable null
jaroslav@1890
   422
     *
jaroslav@1890
   423
     */
jaroslav@1890
   424
    public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
jaroslav@1890
   425
        if (callable == null)
jaroslav@1890
   426
            throw new NullPointerException();
jaroslav@1890
   427
        return new PrivilegedCallable<T>(callable);
jaroslav@1890
   428
    }
jaroslav@1890
   429
jaroslav@1890
   430
    /**
jaroslav@1890
   431
     * Returns a {@link Callable} object that will, when
jaroslav@1890
   432
     * called, execute the given <tt>callable</tt> under the current
jaroslav@1890
   433
     * access control context, with the current context class loader
jaroslav@1890
   434
     * as the context class loader. This method should normally be
jaroslav@1890
   435
     * invoked within an {@link AccessController#doPrivileged} action
jaroslav@1890
   436
     * to create callables that will, if possible, execute under the
jaroslav@1890
   437
     * selected permission settings holding within that action; or if
jaroslav@1890
   438
     * not possible, throw an associated {@link
jaroslav@1890
   439
     * AccessControlException}.
jaroslav@1890
   440
     * @param callable the underlying task
jaroslav@1890
   441
     *
jaroslav@1890
   442
     * @return a callable object
jaroslav@1890
   443
     * @throws NullPointerException if callable null
jaroslav@1890
   444
     * @throws AccessControlException if the current access control
jaroslav@1890
   445
     * context does not have permission to both set and get context
jaroslav@1890
   446
     * class loader.
jaroslav@1890
   447
     */
jaroslav@1890
   448
    public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
jaroslav@1895
   449
        throw new SecurityException();
jaroslav@1890
   450
    }
jaroslav@1890
   451
jaroslav@1890
   452
    // Non-public classes supporting the public methods
jaroslav@1890
   453
jaroslav@1890
   454
    /**
jaroslav@1890
   455
     * A callable that runs given task and returns given result
jaroslav@1890
   456
     */
jaroslav@1890
   457
    static final class RunnableAdapter<T> implements Callable<T> {
jaroslav@1890
   458
        final Runnable task;
jaroslav@1890
   459
        final T result;
jaroslav@1890
   460
        RunnableAdapter(Runnable task, T result) {
jaroslav@1890
   461
            this.task = task;
jaroslav@1890
   462
            this.result = result;
jaroslav@1890
   463
        }
jaroslav@1890
   464
        public T call() {
jaroslav@1890
   465
            task.run();
jaroslav@1890
   466
            return result;
jaroslav@1890
   467
        }
jaroslav@1890
   468
    }
jaroslav@1890
   469
jaroslav@1890
   470
    /**
jaroslav@1890
   471
     * A callable that runs under established access control settings
jaroslav@1890
   472
     */
jaroslav@1890
   473
    static final class PrivilegedCallable<T> implements Callable<T> {
jaroslav@1890
   474
        private final Callable<T> task;
jaroslav@1890
   475
jaroslav@1890
   476
        PrivilegedCallable(Callable<T> task) {
jaroslav@1890
   477
            this.task = task;
jaroslav@1890
   478
        }
jaroslav@1890
   479
jaroslav@1890
   480
        public T call() throws Exception {
jaroslav@1895
   481
            return task.call();
jaroslav@1890
   482
        }
jaroslav@1890
   483
    }
jaroslav@1890
   484
jaroslav@1890
   485
    /**
jaroslav@1890
   486
     * The default thread factory
jaroslav@1890
   487
     */
jaroslav@1890
   488
    static class DefaultThreadFactory implements ThreadFactory {
jaroslav@1890
   489
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
jaroslav@1890
   490
        private final AtomicInteger threadNumber = new AtomicInteger(1);
jaroslav@1890
   491
        private final String namePrefix;
jaroslav@1890
   492
jaroslav@1890
   493
        DefaultThreadFactory() {
jaroslav@1890
   494
            namePrefix = "pool-" +
jaroslav@1890
   495
                          poolNumber.getAndIncrement() +
jaroslav@1890
   496
                         "-thread-";
jaroslav@1890
   497
        }
jaroslav@1890
   498
jaroslav@1890
   499
        public Thread newThread(Runnable r) {
jaroslav@1895
   500
            Thread t = new Thread(r,
jaroslav@1895
   501
                                  namePrefix + threadNumber.getAndIncrement()
jaroslav@1895
   502
                                  );
jaroslav@1890
   503
            if (t.isDaemon())
jaroslav@1890
   504
                t.setDaemon(false);
jaroslav@1890
   505
            if (t.getPriority() != Thread.NORM_PRIORITY)
jaroslav@1890
   506
                t.setPriority(Thread.NORM_PRIORITY);
jaroslav@1890
   507
            return t;
jaroslav@1890
   508
        }
jaroslav@1890
   509
    }
jaroslav@1890
   510
jaroslav@1890
   511
    /**
jaroslav@1890
   512
     * A wrapper class that exposes only the ExecutorService methods
jaroslav@1890
   513
     * of an ExecutorService implementation.
jaroslav@1890
   514
     */
jaroslav@1890
   515
    static class DelegatedExecutorService extends AbstractExecutorService {
jaroslav@1890
   516
        private final ExecutorService e;
jaroslav@1890
   517
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
jaroslav@1890
   518
        public void execute(Runnable command) { e.execute(command); }
jaroslav@1890
   519
        public void shutdown() { e.shutdown(); }
jaroslav@1890
   520
        public List<Runnable> shutdownNow() { return e.shutdownNow(); }
jaroslav@1890
   521
        public boolean isShutdown() { return e.isShutdown(); }
jaroslav@1890
   522
        public boolean isTerminated() { return e.isTerminated(); }
jaroslav@1890
   523
        public boolean awaitTermination(long timeout, TimeUnit unit)
jaroslav@1890
   524
            throws InterruptedException {
jaroslav@1890
   525
            return e.awaitTermination(timeout, unit);
jaroslav@1890
   526
        }
jaroslav@1890
   527
        public Future<?> submit(Runnable task) {
jaroslav@1890
   528
            return e.submit(task);
jaroslav@1890
   529
        }
jaroslav@1890
   530
        public <T> Future<T> submit(Callable<T> task) {
jaroslav@1890
   531
            return e.submit(task);
jaroslav@1890
   532
        }
jaroslav@1890
   533
        public <T> Future<T> submit(Runnable task, T result) {
jaroslav@1890
   534
            return e.submit(task, result);
jaroslav@1890
   535
        }
jaroslav@1890
   536
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
jaroslav@1890
   537
            throws InterruptedException {
jaroslav@1890
   538
            return e.invokeAll(tasks);
jaroslav@1890
   539
        }
jaroslav@1890
   540
        public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
jaroslav@1890
   541
                                             long timeout, TimeUnit unit)
jaroslav@1890
   542
            throws InterruptedException {
jaroslav@1890
   543
            return e.invokeAll(tasks, timeout, unit);
jaroslav@1890
   544
        }
jaroslav@1890
   545
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
jaroslav@1890
   546
            throws InterruptedException, ExecutionException {
jaroslav@1890
   547
            return e.invokeAny(tasks);
jaroslav@1890
   548
        }
jaroslav@1890
   549
        public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
jaroslav@1890
   550
                               long timeout, TimeUnit unit)
jaroslav@1890
   551
            throws InterruptedException, ExecutionException, TimeoutException {
jaroslav@1890
   552
            return e.invokeAny(tasks, timeout, unit);
jaroslav@1890
   553
        }
jaroslav@1890
   554
    }
jaroslav@1890
   555
jaroslav@1890
   556
    static class FinalizableDelegatedExecutorService
jaroslav@1890
   557
        extends DelegatedExecutorService {
jaroslav@1890
   558
        FinalizableDelegatedExecutorService(ExecutorService executor) {
jaroslav@1890
   559
            super(executor);
jaroslav@1890
   560
        }
jaroslav@1890
   561
        protected void finalize() {
jaroslav@1890
   562
            super.shutdown();
jaroslav@1890
   563
        }
jaroslav@1890
   564
    }
jaroslav@1890
   565
jaroslav@1890
   566
    /**
jaroslav@1890
   567
     * A wrapper class that exposes only the ScheduledExecutorService
jaroslav@1890
   568
     * methods of a ScheduledExecutorService implementation.
jaroslav@1890
   569
     */
jaroslav@1890
   570
    static class DelegatedScheduledExecutorService
jaroslav@1890
   571
            extends DelegatedExecutorService
jaroslav@1890
   572
            implements ScheduledExecutorService {
jaroslav@1890
   573
        private final ScheduledExecutorService e;
jaroslav@1890
   574
        DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
jaroslav@1890
   575
            super(executor);
jaroslav@1890
   576
            e = executor;
jaroslav@1890
   577
        }
jaroslav@1890
   578
        public ScheduledFuture<?> schedule(Runnable command, long delay,  TimeUnit unit) {
jaroslav@1890
   579
            return e.schedule(command, delay, unit);
jaroslav@1890
   580
        }
jaroslav@1890
   581
        public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
jaroslav@1890
   582
            return e.schedule(callable, delay, unit);
jaroslav@1890
   583
        }
jaroslav@1890
   584
        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,  long period, TimeUnit unit) {
jaroslav@1890
   585
            return e.scheduleAtFixedRate(command, initialDelay, period, unit);
jaroslav@1890
   586
        }
jaroslav@1890
   587
        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,  long delay, TimeUnit unit) {
jaroslav@1890
   588
            return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
jaroslav@1890
   589
        }
jaroslav@1890
   590
    }
jaroslav@1890
   591
jaroslav@1890
   592
jaroslav@1890
   593
    /** Cannot instantiate. */
jaroslav@1890
   594
    private Executors() {}
jaroslav@1890
   595
}