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