src/java.base/share/classes/java/util/concurrent/ThreadPoolExecutor.java
author dl
Tue, 03 Oct 2017 14:00:00 -0700
changeset 47307 6864969a78ad
parent 47216 71c04702a3d5
child 48541 946e34c2dec9
permissions -rw-r--r--
8186056: Miscellaneous changes imported from jsr166 CVS 2017-09 Reviewed-by: martin, psandoz
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     1
/*
90ce3da70b43 Initial load
duke
parents:
diff changeset
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
90ce3da70b43 Initial load
duke
parents:
diff changeset
     3
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
     4
 * This code is free software; you can redistribute it and/or modify it
90ce3da70b43 Initial load
duke
parents:
diff changeset
     5
 * under the terms of the GNU General Public License version 2 only, as
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 61
diff changeset
     6
 * published by the Free Software Foundation.  Oracle designates this
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     7
 * particular file as subject to the "Classpath" exception as provided
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 61
diff changeset
     8
 * by Oracle in the LICENSE file that accompanied this code.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
     9
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    10
 * This code is distributed in the hope that it will be useful, but WITHOUT
90ce3da70b43 Initial load
duke
parents:
diff changeset
    11
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
90ce3da70b43 Initial load
duke
parents:
diff changeset
    12
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
90ce3da70b43 Initial load
duke
parents:
diff changeset
    13
 * version 2 for more details (a copy is included in the LICENSE file that
90ce3da70b43 Initial load
duke
parents:
diff changeset
    14
 * accompanied this code).
90ce3da70b43 Initial load
duke
parents:
diff changeset
    15
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    16
 * You should have received a copy of the GNU General Public License version
90ce3da70b43 Initial load
duke
parents:
diff changeset
    17
 * 2 along with this work; if not, write to the Free Software Foundation,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    18
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    19
 *
5506
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 61
diff changeset
    20
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 61
diff changeset
    21
 * or visit www.oracle.com if you need additional information or have any
202f599c92aa 6943119: Rebrand source copyright notices
ohair
parents: 61
diff changeset
    22
 * questions.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    23
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
    24
90ce3da70b43 Initial load
duke
parents:
diff changeset
    25
/*
90ce3da70b43 Initial load
duke
parents:
diff changeset
    26
 * This file is available under and governed by the GNU General Public
90ce3da70b43 Initial load
duke
parents:
diff changeset
    27
 * License version 2 only, as published by the Free Software Foundation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    28
 * However, the following notice accompanied the original version of this
90ce3da70b43 Initial load
duke
parents:
diff changeset
    29
 * file:
90ce3da70b43 Initial load
duke
parents:
diff changeset
    30
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    31
 * Written by Doug Lea with assistance from members of JCP JSR-166
90ce3da70b43 Initial load
duke
parents:
diff changeset
    32
 * Expert Group and released to the public domain, as explained at
9242
ef138d47df58 7034657: Update Creative Commons license URL in legal notices
dl
parents: 7976
diff changeset
    33
 * http://creativecommons.org/publicdomain/zero/1.0/
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    34
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
    35
90ce3da70b43 Initial load
duke
parents:
diff changeset
    36
package java.util.concurrent;
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    37
45978
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
    38
import java.security.AccessControlContext;
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
    39
import java.security.AccessController;
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
    40
import java.security.PrivilegedAction;
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    41
import java.util.ArrayList;
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    42
import java.util.ConcurrentModificationException;
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    43
import java.util.HashSet;
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    44
import java.util.Iterator;
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    45
import java.util.List;
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
    46
import java.util.concurrent.atomic.AtomicInteger;
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
    47
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
    48
import java.util.concurrent.locks.Condition;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
    49
import java.util.concurrent.locks.ReentrantLock;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    50
90ce3da70b43 Initial load
duke
parents:
diff changeset
    51
/**
90ce3da70b43 Initial load
duke
parents:
diff changeset
    52
 * An {@link ExecutorService} that executes each submitted task using
90ce3da70b43 Initial load
duke
parents:
diff changeset
    53
 * one of possibly several pooled threads, normally configured
90ce3da70b43 Initial load
duke
parents:
diff changeset
    54
 * using {@link Executors} factory methods.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    55
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    56
 * <p>Thread pools address two different problems: they usually
90ce3da70b43 Initial load
duke
parents:
diff changeset
    57
 * provide improved performance when executing large numbers of
90ce3da70b43 Initial load
duke
parents:
diff changeset
    58
 * asynchronous tasks, due to reduced per-task invocation overhead,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    59
 * and they provide a means of bounding and managing the resources,
90ce3da70b43 Initial load
duke
parents:
diff changeset
    60
 * including threads, consumed when executing a collection of tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    61
 * Each {@code ThreadPoolExecutor} also maintains some basic
90ce3da70b43 Initial load
duke
parents:
diff changeset
    62
 * statistics, such as the number of completed tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
    63
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    64
 * <p>To be useful across a wide range of contexts, this class
90ce3da70b43 Initial load
duke
parents:
diff changeset
    65
 * provides many adjustable parameters and extensibility
90ce3da70b43 Initial load
duke
parents:
diff changeset
    66
 * hooks. However, programmers are urged to use the more convenient
90ce3da70b43 Initial load
duke
parents:
diff changeset
    67
 * {@link Executors} factory methods {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
    68
 * Executors#newCachedThreadPool} (unbounded thread pool, with
90ce3da70b43 Initial load
duke
parents:
diff changeset
    69
 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
90ce3da70b43 Initial load
duke
parents:
diff changeset
    70
 * (fixed size thread pool) and {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
    71
 * Executors#newSingleThreadExecutor} (single background thread), that
90ce3da70b43 Initial load
duke
parents:
diff changeset
    72
 * preconfigure settings for the most common usage
90ce3da70b43 Initial load
duke
parents:
diff changeset
    73
 * scenarios. Otherwise, use the following guide when manually
90ce3da70b43 Initial load
duke
parents:
diff changeset
    74
 * configuring and tuning this class:
90ce3da70b43 Initial load
duke
parents:
diff changeset
    75
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    76
 * <dl>
90ce3da70b43 Initial load
duke
parents:
diff changeset
    77
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    78
 * <dt>Core and maximum pool sizes</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
    79
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    80
 * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    81
 * pool size (see {@link #getPoolSize})
90ce3da70b43 Initial load
duke
parents:
diff changeset
    82
 * according to the bounds set by
90ce3da70b43 Initial load
duke
parents:
diff changeset
    83
 * corePoolSize (see {@link #getCorePoolSize}) and
90ce3da70b43 Initial load
duke
parents:
diff changeset
    84
 * maximumPoolSize (see {@link #getMaximumPoolSize}).
90ce3da70b43 Initial load
duke
parents:
diff changeset
    85
 *
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
    86
 * When a new task is submitted in method {@link #execute(Runnable)},
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    87
 * if fewer than corePoolSize threads are running, a new thread is
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
    88
 * created to handle the request, even if other worker threads are
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    89
 * idle.  Else if fewer than maximumPoolSize threads are running, a
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    90
 * new thread will be created to handle the request only if the queue
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    91
 * is full.  By setting corePoolSize and maximumPoolSize the same, you
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    92
 * create a fixed-size thread pool. By setting maximumPoolSize to an
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    93
 * essentially unbounded value such as {@code Integer.MAX_VALUE}, you
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    94
 * allow the pool to accommodate an arbitrary number of concurrent
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    95
 * tasks. Most typically, core and maximum pool sizes are set only
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    96
 * upon construction, but they may also be changed dynamically using
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
    97
 * {@link #setCorePoolSize} and {@link #setMaximumPoolSize}. </dd>
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
    98
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
    99
 * <dt>On-demand construction</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   100
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   101
 * <dd>By default, even core threads are initially created and
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   102
 * started only when new tasks arrive, but this can be overridden
90ce3da70b43 Initial load
duke
parents:
diff changeset
   103
 * dynamically using method {@link #prestartCoreThread} or {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
   104
 * #prestartAllCoreThreads}.  You probably want to prestart threads if
90ce3da70b43 Initial load
duke
parents:
diff changeset
   105
 * you construct the pool with a non-empty queue. </dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   106
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   107
 * <dt>Creating new threads</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   108
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   109
 * <dd>New threads are created using a {@link ThreadFactory}.  If not
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   110
 * otherwise specified, a {@link Executors#defaultThreadFactory} is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   111
 * used, that creates threads to all be in the same {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
   112
 * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
90ce3da70b43 Initial load
duke
parents:
diff changeset
   113
 * non-daemon status. By supplying a different ThreadFactory, you can
90ce3da70b43 Initial load
duke
parents:
diff changeset
   114
 * alter the thread's name, thread group, priority, daemon status,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   115
 * etc. If a {@code ThreadFactory} fails to create a thread when asked
90ce3da70b43 Initial load
duke
parents:
diff changeset
   116
 * by returning null from {@code newThread}, the executor will
90ce3da70b43 Initial load
duke
parents:
diff changeset
   117
 * continue, but might not be able to execute any tasks. Threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
   118
 * should possess the "modifyThread" {@code RuntimePermission}. If
90ce3da70b43 Initial load
duke
parents:
diff changeset
   119
 * worker threads or other threads using the pool do not possess this
90ce3da70b43 Initial load
duke
parents:
diff changeset
   120
 * permission, service may be degraded: configuration changes may not
90ce3da70b43 Initial load
duke
parents:
diff changeset
   121
 * take effect in a timely manner, and a shutdown pool may remain in a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   122
 * state in which termination is possible but not completed.</dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   123
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   124
 * <dt>Keep-alive times</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   125
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   126
 * <dd>If the pool currently has more than corePoolSize threads,
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   127
 * excess threads will be terminated if they have been idle for more
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   128
 * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   129
 * This provides a means of reducing resource consumption when the
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   130
 * pool is not being actively used. If the pool becomes more active
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   131
 * later, new threads will be constructed. This parameter can also be
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   132
 * changed dynamically using method {@link #setKeepAliveTime(long,
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   133
 * TimeUnit)}.  Using a value of {@code Long.MAX_VALUE} {@link
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   134
 * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   135
 * terminating prior to shut down. By default, the keep-alive policy
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   136
 * applies only when there are more than corePoolSize threads, but
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   137
 * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   138
 * apply this time-out policy to core threads as well, so long as the
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   139
 * keepAliveTime value is non-zero. </dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   140
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   141
 * <dt>Queuing</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   142
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   143
 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   144
 * submitted tasks.  The use of this queue interacts with pool sizing:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   145
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   146
 * <ul>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   147
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   148
 * <li>If fewer than corePoolSize threads are running, the Executor
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   149
 * always prefers adding a new thread
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   150
 * rather than queuing.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   151
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   152
 * <li>If corePoolSize or more threads are running, the Executor
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   153
 * always prefers queuing a request rather than adding a new
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   154
 * thread.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   155
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   156
 * <li>If a request cannot be queued, a new thread is created unless
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   157
 * this would exceed maximumPoolSize, in which case, the task will be
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   158
 * rejected.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   159
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   160
 * </ul>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   161
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   162
 * There are three general strategies for queuing:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   163
 * <ol>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   164
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   165
 * <li><em> Direct handoffs.</em> A good default choice for a work
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   166
 * queue is a {@link SynchronousQueue} that hands off tasks to threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
   167
 * without otherwise holding them. Here, an attempt to queue a task
90ce3da70b43 Initial load
duke
parents:
diff changeset
   168
 * will fail if no threads are immediately available to run it, so a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   169
 * new thread will be constructed. This policy avoids lockups when
90ce3da70b43 Initial load
duke
parents:
diff changeset
   170
 * handling sets of requests that might have internal dependencies.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   171
 * Direct handoffs generally require unbounded maximumPoolSizes to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   172
 * avoid rejection of new submitted tasks. This in turn admits the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   173
 * possibility of unbounded thread growth when commands continue to
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   174
 * arrive on average faster than they can be processed.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   175
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   176
 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   177
 * example a {@link LinkedBlockingQueue} without a predefined
90ce3da70b43 Initial load
duke
parents:
diff changeset
   178
 * capacity) will cause new tasks to wait in the queue when all
90ce3da70b43 Initial load
duke
parents:
diff changeset
   179
 * corePoolSize threads are busy. Thus, no more than corePoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
   180
 * threads will ever be created. (And the value of the maximumPoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
   181
 * therefore doesn't have any effect.)  This may be appropriate when
90ce3da70b43 Initial load
duke
parents:
diff changeset
   182
 * each task is completely independent of others, so tasks cannot
90ce3da70b43 Initial load
duke
parents:
diff changeset
   183
 * affect each others execution; for example, in a web page server.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   184
 * While this style of queuing can be useful in smoothing out
90ce3da70b43 Initial load
duke
parents:
diff changeset
   185
 * transient bursts of requests, it admits the possibility of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   186
 * unbounded work queue growth when commands continue to arrive on
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   187
 * average faster than they can be processed.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   188
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   189
 * <li><em>Bounded queues.</em> A bounded queue (for example, an
90ce3da70b43 Initial load
duke
parents:
diff changeset
   190
 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
90ce3da70b43 Initial load
duke
parents:
diff changeset
   191
 * used with finite maximumPoolSizes, but can be more difficult to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   192
 * tune and control.  Queue sizes and maximum pool sizes may be traded
90ce3da70b43 Initial load
duke
parents:
diff changeset
   193
 * off for each other: Using large queues and small pools minimizes
90ce3da70b43 Initial load
duke
parents:
diff changeset
   194
 * CPU usage, OS resources, and context-switching overhead, but can
90ce3da70b43 Initial load
duke
parents:
diff changeset
   195
 * lead to artificially low throughput.  If tasks frequently block (for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   196
 * example if they are I/O bound), a system may be able to schedule
90ce3da70b43 Initial load
duke
parents:
diff changeset
   197
 * time for more threads than you otherwise allow. Use of small queues
90ce3da70b43 Initial load
duke
parents:
diff changeset
   198
 * generally requires larger pool sizes, which keeps CPUs busier but
90ce3da70b43 Initial load
duke
parents:
diff changeset
   199
 * may encounter unacceptable scheduling overhead, which also
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   200
 * decreases throughput.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   201
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   202
 * </ol>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   203
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   204
 * </dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   205
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   206
 * <dt>Rejected tasks</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   207
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   208
 * <dd>New tasks submitted in method {@link #execute(Runnable)} will be
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   209
 * <em>rejected</em> when the Executor has been shut down, and also when
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   210
 * the Executor uses finite bounds for both maximum threads and work queue
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   211
 * capacity, and is saturated.  In either case, the {@code execute} method
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   212
 * invokes the {@link
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   213
 * RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   214
 * method of its {@link RejectedExecutionHandler}.  Four predefined handler
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   215
 * policies are provided:
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   216
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   217
 * <ol>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   218
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   219
 * <li>In the default {@link ThreadPoolExecutor.AbortPolicy}, the handler
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   220
 * throws a runtime {@link RejectedExecutionException} upon rejection.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   221
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   222
 * <li>In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   223
 * that invokes {@code execute} itself runs the task. This provides a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   224
 * simple feedback control mechanism that will slow down the rate that
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   225
 * new tasks are submitted.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   226
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   227
 * <li>In {@link ThreadPoolExecutor.DiscardPolicy}, a task that
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   228
 * cannot be executed is simply dropped.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   229
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   230
 * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   231
 * executor is not shut down, the task at the head of the work queue
90ce3da70b43 Initial load
duke
parents:
diff changeset
   232
 * is dropped, and then execution is retried (which can fail again,
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   233
 * causing this to be repeated.)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   234
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   235
 * </ol>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   236
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   237
 * It is possible to define and use other kinds of {@link
90ce3da70b43 Initial load
duke
parents:
diff changeset
   238
 * RejectedExecutionHandler} classes. Doing so requires some care
90ce3da70b43 Initial load
duke
parents:
diff changeset
   239
 * especially when policies are designed to work only under particular
90ce3da70b43 Initial load
duke
parents:
diff changeset
   240
 * capacity or queuing policies. </dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   241
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   242
 * <dt>Hook methods</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   243
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   244
 * <dd>This class provides {@code protected} overridable
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   245
 * {@link #beforeExecute(Thread, Runnable)} and
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   246
 * {@link #afterExecute(Runnable, Throwable)} methods that are called
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   247
 * before and after execution of each task.  These can be used to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   248
 * manipulate the execution environment; for example, reinitializing
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   249
 * ThreadLocals, gathering statistics, or adding log entries.
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   250
 * Additionally, method {@link #terminated} can be overridden to perform
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   251
 * any special processing that needs to be done once the Executor has
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   252
 * fully terminated.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   253
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   254
 * <p>If hook, callback, or BlockingQueue methods throw exceptions,
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   255
 * internal worker threads may in turn fail, abruptly terminate, and
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   256
 * possibly be replaced.</dd>
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   257
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   258
 * <dt>Queue maintenance</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   259
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   260
 * <dd>Method {@link #getQueue()} allows access to the work queue
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   261
 * for purposes of monitoring and debugging.  Use of this method for
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   262
 * any other purpose is strongly discouraged.  Two supplied methods,
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   263
 * {@link #remove(Runnable)} and {@link #purge} are available to
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   264
 * assist in storage reclamation when large numbers of queued tasks
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   265
 * become cancelled.</dd>
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   266
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   267
 * <dt>Finalization</dt>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   268
 *
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
   269
 * <dd>A pool that is no longer referenced in a program <em>AND</em>
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   270
 * has no remaining threads will be {@code shutdown} automatically. If
90ce3da70b43 Initial load
duke
parents:
diff changeset
   271
 * you would like to ensure that unreferenced pools are reclaimed even
90ce3da70b43 Initial load
duke
parents:
diff changeset
   272
 * if users forget to call {@link #shutdown}, then you must arrange
90ce3da70b43 Initial load
duke
parents:
diff changeset
   273
 * that unused threads eventually die, by setting appropriate
90ce3da70b43 Initial load
duke
parents:
diff changeset
   274
 * keep-alive times, using a lower bound of zero core threads and/or
90ce3da70b43 Initial load
duke
parents:
diff changeset
   275
 * setting {@link #allowCoreThreadTimeOut(boolean)}.  </dd>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   276
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   277
 * </dl>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   278
 *
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   279
 * <p><b>Extension example</b>. Most extensions of this class
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   280
 * override one or more of the protected hook methods. For example,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   281
 * here is a subclass that adds a simple pause/resume feature:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   282
 *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   283
 * <pre> {@code
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   284
 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   285
 *   private boolean isPaused;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   286
 *   private ReentrantLock pauseLock = new ReentrantLock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   287
 *   private Condition unpaused = pauseLock.newCondition();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   288
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   289
 *   public PausableThreadPoolExecutor(...) { super(...); }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   290
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   291
 *   protected void beforeExecute(Thread t, Runnable r) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   292
 *     super.beforeExecute(t, r);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   293
 *     pauseLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   294
 *     try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   295
 *       while (isPaused) unpaused.await();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   296
 *     } catch (InterruptedException ie) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   297
 *       t.interrupt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   298
 *     } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   299
 *       pauseLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   300
 *     }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   301
 *   }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   302
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   303
 *   public void pause() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   304
 *     pauseLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   305
 *     try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   306
 *       isPaused = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   307
 *     } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   308
 *       pauseLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   309
 *     }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   310
 *   }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   311
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   312
 *   public void resume() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   313
 *     pauseLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   314
 *     try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   315
 *       isPaused = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   316
 *       unpaused.signalAll();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   317
 *     } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   318
 *       pauseLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   319
 *     }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   320
 *   }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   321
 * }}</pre>
90ce3da70b43 Initial load
duke
parents:
diff changeset
   322
 *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   323
 * @since 1.5
90ce3da70b43 Initial load
duke
parents:
diff changeset
   324
 * @author Doug Lea
90ce3da70b43 Initial load
duke
parents:
diff changeset
   325
 */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   326
public class ThreadPoolExecutor extends AbstractExecutorService {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   327
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   328
     * The main pool control state, ctl, is an atomic integer packing
90ce3da70b43 Initial load
duke
parents:
diff changeset
   329
     * two conceptual fields
90ce3da70b43 Initial load
duke
parents:
diff changeset
   330
     *   workerCount, indicating the effective number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
   331
     *   runState,    indicating whether running, shutting down etc
90ce3da70b43 Initial load
duke
parents:
diff changeset
   332
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   333
     * In order to pack them into one int, we limit workerCount to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   334
     * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   335
     * billion) otherwise representable. If this is ever an issue in
90ce3da70b43 Initial load
duke
parents:
diff changeset
   336
     * the future, the variable can be changed to be an AtomicLong,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   337
     * and the shift/mask constants below adjusted. But until the need
90ce3da70b43 Initial load
duke
parents:
diff changeset
   338
     * arises, this code is a bit faster and simpler using an int.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   339
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   340
     * The workerCount is the number of workers that have been
90ce3da70b43 Initial load
duke
parents:
diff changeset
   341
     * permitted to start and not permitted to stop.  The value may be
90ce3da70b43 Initial load
duke
parents:
diff changeset
   342
     * transiently different from the actual number of live threads,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   343
     * for example when a ThreadFactory fails to create a thread when
90ce3da70b43 Initial load
duke
parents:
diff changeset
   344
     * asked, and when exiting threads are still performing
90ce3da70b43 Initial load
duke
parents:
diff changeset
   345
     * bookkeeping before terminating. The user-visible pool size is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   346
     * reported as the current size of the workers set.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   347
     *
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   348
     * The runState provides the main lifecycle control, taking on values:
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   349
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   350
     *   RUNNING:  Accept new tasks and process queued tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
   351
     *   SHUTDOWN: Don't accept new tasks, but process queued tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
   352
     *   STOP:     Don't accept new tasks, don't process queued tasks,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   353
     *             and interrupt in-progress tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
   354
     *   TIDYING:  All tasks have terminated, workerCount is zero,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   355
     *             the thread transitioning to state TIDYING
90ce3da70b43 Initial load
duke
parents:
diff changeset
   356
     *             will run the terminated() hook method
90ce3da70b43 Initial load
duke
parents:
diff changeset
   357
     *   TERMINATED: terminated() has completed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   358
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   359
     * The numerical order among these values matters, to allow
90ce3da70b43 Initial load
duke
parents:
diff changeset
   360
     * ordered comparisons. The runState monotonically increases over
90ce3da70b43 Initial load
duke
parents:
diff changeset
   361
     * time, but need not hit each state. The transitions are:
90ce3da70b43 Initial load
duke
parents:
diff changeset
   362
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   363
     * RUNNING -> SHUTDOWN
90ce3da70b43 Initial load
duke
parents:
diff changeset
   364
     *    On invocation of shutdown(), perhaps implicitly in finalize()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   365
     * (RUNNING or SHUTDOWN) -> STOP
90ce3da70b43 Initial load
duke
parents:
diff changeset
   366
     *    On invocation of shutdownNow()
90ce3da70b43 Initial load
duke
parents:
diff changeset
   367
     * SHUTDOWN -> TIDYING
90ce3da70b43 Initial load
duke
parents:
diff changeset
   368
     *    When both queue and pool are empty
90ce3da70b43 Initial load
duke
parents:
diff changeset
   369
     * STOP -> TIDYING
90ce3da70b43 Initial load
duke
parents:
diff changeset
   370
     *    When pool is empty
90ce3da70b43 Initial load
duke
parents:
diff changeset
   371
     * TIDYING -> TERMINATED
90ce3da70b43 Initial load
duke
parents:
diff changeset
   372
     *    When the terminated() hook method has completed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   373
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   374
     * Threads waiting in awaitTermination() will return when the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   375
     * state reaches TERMINATED.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   376
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   377
     * Detecting the transition from SHUTDOWN to TIDYING is less
90ce3da70b43 Initial load
duke
parents:
diff changeset
   378
     * straightforward than you'd like because the queue may become
90ce3da70b43 Initial load
duke
parents:
diff changeset
   379
     * empty after non-empty and vice versa during SHUTDOWN state, but
90ce3da70b43 Initial load
duke
parents:
diff changeset
   380
     * we can only terminate if, after seeing that it is empty, we see
90ce3da70b43 Initial load
duke
parents:
diff changeset
   381
     * that workerCount is 0 (which sometimes entails a recheck -- see
90ce3da70b43 Initial load
duke
parents:
diff changeset
   382
     * below).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   383
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   384
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   385
    private static final int COUNT_BITS = Integer.SIZE - 3;
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   386
    private static final int COUNT_MASK = (1 << COUNT_BITS) - 1;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   387
90ce3da70b43 Initial load
duke
parents:
diff changeset
   388
    // runState is stored in the high-order bits
90ce3da70b43 Initial load
duke
parents:
diff changeset
   389
    private static final int RUNNING    = -1 << COUNT_BITS;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   390
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   391
    private static final int STOP       =  1 << COUNT_BITS;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   392
    private static final int TIDYING    =  2 << COUNT_BITS;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   393
    private static final int TERMINATED =  3 << COUNT_BITS;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   394
90ce3da70b43 Initial load
duke
parents:
diff changeset
   395
    // Packing and unpacking ctl
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   396
    private static int runStateOf(int c)     { return c & ~COUNT_MASK; }
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   397
    private static int workerCountOf(int c)  { return c & COUNT_MASK; }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   398
    private static int ctlOf(int rs, int wc) { return rs | wc; }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   399
90ce3da70b43 Initial load
duke
parents:
diff changeset
   400
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   401
     * Bit field accessors that don't require unpacking ctl.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   402
     * These depend on the bit layout and on workerCount being never negative.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   403
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   404
90ce3da70b43 Initial load
duke
parents:
diff changeset
   405
    private static boolean runStateLessThan(int c, int s) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   406
        return c < s;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   407
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   408
90ce3da70b43 Initial load
duke
parents:
diff changeset
   409
    private static boolean runStateAtLeast(int c, int s) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   410
        return c >= s;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   411
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   412
90ce3da70b43 Initial load
duke
parents:
diff changeset
   413
    private static boolean isRunning(int c) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   414
        return c < SHUTDOWN;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   415
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   416
90ce3da70b43 Initial load
duke
parents:
diff changeset
   417
    /**
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   418
     * Attempts to CAS-increment the workerCount field of ctl.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   419
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   420
    private boolean compareAndIncrementWorkerCount(int expect) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   421
        return ctl.compareAndSet(expect, expect + 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   422
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   423
90ce3da70b43 Initial load
duke
parents:
diff changeset
   424
    /**
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   425
     * Attempts to CAS-decrement the workerCount field of ctl.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   426
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   427
    private boolean compareAndDecrementWorkerCount(int expect) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   428
        return ctl.compareAndSet(expect, expect - 1);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   429
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   430
90ce3da70b43 Initial load
duke
parents:
diff changeset
   431
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   432
     * Decrements the workerCount field of ctl. This is called only on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   433
     * abrupt termination of a thread (see processWorkerExit). Other
90ce3da70b43 Initial load
duke
parents:
diff changeset
   434
     * decrements are performed within getTask.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   435
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   436
    private void decrementWorkerCount() {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   437
        ctl.addAndGet(-1);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   438
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   439
90ce3da70b43 Initial load
duke
parents:
diff changeset
   440
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   441
     * The queue used for holding tasks and handing off to worker
90ce3da70b43 Initial load
duke
parents:
diff changeset
   442
     * threads.  We do not require that workQueue.poll() returning
90ce3da70b43 Initial load
duke
parents:
diff changeset
   443
     * null necessarily means that workQueue.isEmpty(), so rely
90ce3da70b43 Initial load
duke
parents:
diff changeset
   444
     * solely on isEmpty to see if the queue is empty (which we must
90ce3da70b43 Initial load
duke
parents:
diff changeset
   445
     * do for example when deciding whether to transition from
90ce3da70b43 Initial load
duke
parents:
diff changeset
   446
     * SHUTDOWN to TIDYING).  This accommodates special-purpose
90ce3da70b43 Initial load
duke
parents:
diff changeset
   447
     * queues such as DelayQueues for which poll() is allowed to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   448
     * return null even if it may later return non-null when delays
90ce3da70b43 Initial load
duke
parents:
diff changeset
   449
     * expire.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   450
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   451
    private final BlockingQueue<Runnable> workQueue;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   452
90ce3da70b43 Initial load
duke
parents:
diff changeset
   453
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   454
     * Lock held on access to workers set and related bookkeeping.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   455
     * While we could use a concurrent set of some sort, it turns out
90ce3da70b43 Initial load
duke
parents:
diff changeset
   456
     * to be generally preferable to use a lock. Among the reasons is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   457
     * that this serializes interruptIdleWorkers, which avoids
90ce3da70b43 Initial load
duke
parents:
diff changeset
   458
     * unnecessary interrupt storms, especially during shutdown.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   459
     * Otherwise exiting threads would concurrently interrupt those
90ce3da70b43 Initial load
duke
parents:
diff changeset
   460
     * that have not yet interrupted. It also simplifies some of the
90ce3da70b43 Initial load
duke
parents:
diff changeset
   461
     * associated statistics bookkeeping of largestPoolSize etc. We
90ce3da70b43 Initial load
duke
parents:
diff changeset
   462
     * also hold mainLock on shutdown and shutdownNow, for the sake of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   463
     * ensuring workers set is stable while separately checking
90ce3da70b43 Initial load
duke
parents:
diff changeset
   464
     * permission to interrupt and actually interrupting.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   465
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   466
    private final ReentrantLock mainLock = new ReentrantLock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   467
90ce3da70b43 Initial load
duke
parents:
diff changeset
   468
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   469
     * Set containing all worker threads in pool. Accessed only when
90ce3da70b43 Initial load
duke
parents:
diff changeset
   470
     * holding mainLock.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   471
     */
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   472
    private final HashSet<Worker> workers = new HashSet<>();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   473
90ce3da70b43 Initial load
duke
parents:
diff changeset
   474
    /**
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   475
     * Wait condition to support awaitTermination.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   476
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   477
    private final Condition termination = mainLock.newCondition();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   478
90ce3da70b43 Initial load
duke
parents:
diff changeset
   479
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   480
     * Tracks largest attained pool size. Accessed only under
90ce3da70b43 Initial load
duke
parents:
diff changeset
   481
     * mainLock.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   482
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   483
    private int largestPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   484
90ce3da70b43 Initial load
duke
parents:
diff changeset
   485
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   486
     * Counter for completed tasks. Updated only on termination of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   487
     * worker threads. Accessed only under mainLock.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   488
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   489
    private long completedTaskCount;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   490
90ce3da70b43 Initial load
duke
parents:
diff changeset
   491
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   492
     * All user control parameters are declared as volatiles so that
90ce3da70b43 Initial load
duke
parents:
diff changeset
   493
     * ongoing actions are based on freshest values, but without need
90ce3da70b43 Initial load
duke
parents:
diff changeset
   494
     * for locking, since no internal invariants depend on them
90ce3da70b43 Initial load
duke
parents:
diff changeset
   495
     * changing synchronously with respect to other actions.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   496
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   497
90ce3da70b43 Initial load
duke
parents:
diff changeset
   498
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   499
     * Factory for new threads. All threads are created using this
90ce3da70b43 Initial load
duke
parents:
diff changeset
   500
     * factory (via method addWorker).  All callers must be prepared
90ce3da70b43 Initial load
duke
parents:
diff changeset
   501
     * for addWorker to fail, which may reflect a system or user's
90ce3da70b43 Initial load
duke
parents:
diff changeset
   502
     * policy limiting the number of threads.  Even though it is not
90ce3da70b43 Initial load
duke
parents:
diff changeset
   503
     * treated as an error, failure to create threads may result in
90ce3da70b43 Initial load
duke
parents:
diff changeset
   504
     * new tasks being rejected or existing ones remaining stuck in
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   505
     * the queue.
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   506
     *
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   507
     * We go further and preserve pool invariants even in the face of
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   508
     * errors such as OutOfMemoryError, that might be thrown while
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   509
     * trying to create threads.  Such errors are rather common due to
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   510
     * the need to allocate a native stack in Thread.start, and users
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   511
     * will want to perform clean pool shutdown to clean up.  There
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   512
     * will likely be enough memory available for the cleanup code to
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   513
     * complete without encountering yet another OutOfMemoryError.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   514
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   515
    private volatile ThreadFactory threadFactory;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   516
90ce3da70b43 Initial load
duke
parents:
diff changeset
   517
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   518
     * Handler called when saturated or shutdown in execute.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   519
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   520
    private volatile RejectedExecutionHandler handler;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   521
90ce3da70b43 Initial load
duke
parents:
diff changeset
   522
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   523
     * Timeout in nanoseconds for idle threads waiting for work.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   524
     * Threads use this timeout when there are more than corePoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
   525
     * present or if allowCoreThreadTimeOut. Otherwise they wait
90ce3da70b43 Initial load
duke
parents:
diff changeset
   526
     * forever for new work.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   527
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   528
    private volatile long keepAliveTime;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   529
90ce3da70b43 Initial load
duke
parents:
diff changeset
   530
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   531
     * If false (default), core threads stay alive even when idle.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   532
     * If true, core threads use keepAliveTime to time out waiting
90ce3da70b43 Initial load
duke
parents:
diff changeset
   533
     * for work.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   534
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   535
    private volatile boolean allowCoreThreadTimeOut;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   536
90ce3da70b43 Initial load
duke
parents:
diff changeset
   537
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   538
     * Core pool size is the minimum number of workers to keep alive
90ce3da70b43 Initial load
duke
parents:
diff changeset
   539
     * (and not allow to time out etc) unless allowCoreThreadTimeOut
90ce3da70b43 Initial load
duke
parents:
diff changeset
   540
     * is set, in which case the minimum is zero.
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   541
     *
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   542
     * Since the worker count is actually stored in COUNT_BITS bits,
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   543
     * the effective limit is {@code corePoolSize & COUNT_MASK}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   544
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   545
    private volatile int corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   546
90ce3da70b43 Initial load
duke
parents:
diff changeset
   547
    /**
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   548
     * Maximum pool size.
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   549
     *
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   550
     * Since the worker count is actually stored in COUNT_BITS bits,
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   551
     * the effective limit is {@code maximumPoolSize & COUNT_MASK}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   552
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   553
    private volatile int maximumPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   554
90ce3da70b43 Initial load
duke
parents:
diff changeset
   555
    /**
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   556
     * The default rejected execution handler.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   557
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   558
    private static final RejectedExecutionHandler defaultHandler =
90ce3da70b43 Initial load
duke
parents:
diff changeset
   559
        new AbortPolicy();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   560
90ce3da70b43 Initial load
duke
parents:
diff changeset
   561
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   562
     * Permission required for callers of shutdown and shutdownNow.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   563
     * We additionally require (see checkShutdownAccess) that callers
90ce3da70b43 Initial load
duke
parents:
diff changeset
   564
     * have permission to actually interrupt threads in the worker set
90ce3da70b43 Initial load
duke
parents:
diff changeset
   565
     * (as governed by Thread.interrupt, which relies on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   566
     * ThreadGroup.checkAccess, which in turn relies on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   567
     * SecurityManager.checkAccess). Shutdowns are attempted only if
90ce3da70b43 Initial load
duke
parents:
diff changeset
   568
     * these checks pass.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   569
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   570
     * All actual invocations of Thread.interrupt (see
90ce3da70b43 Initial load
duke
parents:
diff changeset
   571
     * interruptIdleWorkers and interruptWorkers) ignore
90ce3da70b43 Initial load
duke
parents:
diff changeset
   572
     * SecurityExceptions, meaning that the attempted interrupts
90ce3da70b43 Initial load
duke
parents:
diff changeset
   573
     * silently fail. In the case of shutdown, they should not fail
90ce3da70b43 Initial load
duke
parents:
diff changeset
   574
     * unless the SecurityManager has inconsistent policies, sometimes
90ce3da70b43 Initial load
duke
parents:
diff changeset
   575
     * allowing access to a thread and sometimes not. In such cases,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   576
     * failure to actually interrupt threads may disable or delay full
90ce3da70b43 Initial load
duke
parents:
diff changeset
   577
     * termination. Other uses of interruptIdleWorkers are advisory,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   578
     * and failure to actually interrupt will merely delay response to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   579
     * configuration changes so is not handled exceptionally.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   580
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   581
    private static final RuntimePermission shutdownPerm =
90ce3da70b43 Initial load
duke
parents:
diff changeset
   582
        new RuntimePermission("modifyThread");
90ce3da70b43 Initial load
duke
parents:
diff changeset
   583
46146
b3e220a04d3f 8185099: Miscellaneous changes imported from jsr166 CVS 2017-08
dl
parents: 46041
diff changeset
   584
    /** The context to be used when executing the finalizer, or null. */
45978
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
   585
    private final AccessControlContext acc;
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
   586
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   587
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   588
     * Class Worker mainly maintains interrupt control state for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   589
     * threads running tasks, along with other minor bookkeeping.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   590
     * This class opportunistically extends AbstractQueuedSynchronizer
90ce3da70b43 Initial load
duke
parents:
diff changeset
   591
     * to simplify acquiring and releasing a lock surrounding each
90ce3da70b43 Initial load
duke
parents:
diff changeset
   592
     * task execution.  This protects against interrupts that are
90ce3da70b43 Initial load
duke
parents:
diff changeset
   593
     * intended to wake up a worker thread waiting for a task from
90ce3da70b43 Initial load
duke
parents:
diff changeset
   594
     * instead interrupting a task being run.  We implement a simple
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   595
     * non-reentrant mutual exclusion lock rather than use
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   596
     * ReentrantLock because we do not want worker tasks to be able to
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   597
     * reacquire the lock when they invoke pool control methods like
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   598
     * setCorePoolSize.  Additionally, to suppress interrupts until
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   599
     * the thread actually starts running tasks, we initialize lock
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   600
     * state to a negative value, and clear it upon start (in
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   601
     * runWorker).
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   602
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   603
    private final class Worker
90ce3da70b43 Initial load
duke
parents:
diff changeset
   604
        extends AbstractQueuedSynchronizer
90ce3da70b43 Initial load
duke
parents:
diff changeset
   605
        implements Runnable
90ce3da70b43 Initial load
duke
parents:
diff changeset
   606
    {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   607
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   608
         * This class will never be serialized, but we provide a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   609
         * serialVersionUID to suppress a javac warning.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   610
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   611
        private static final long serialVersionUID = 6138294804551838833L;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   612
90ce3da70b43 Initial load
duke
parents:
diff changeset
   613
        /** Thread this worker is running in.  Null if factory fails. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   614
        final Thread thread;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   615
        /** Initial task to run.  Possibly null. */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   616
        Runnable firstTask;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   617
        /** Per-thread task counter */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   618
        volatile long completedTasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   619
40817
4f5fb115676d 8164169: Miscellaneous changes imported from jsr166 CVS 2016-09
dl
parents: 32991
diff changeset
   620
        // TODO: switch to AbstractQueuedLongSynchronizer and move
4f5fb115676d 8164169: Miscellaneous changes imported from jsr166 CVS 2016-09
dl
parents: 32991
diff changeset
   621
        // completedTasks into the lock word.
4f5fb115676d 8164169: Miscellaneous changes imported from jsr166 CVS 2016-09
dl
parents: 32991
diff changeset
   622
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   623
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   624
         * Creates with given first task and thread from ThreadFactory.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   625
         * @param firstTask the first task (null if none)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   626
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   627
        Worker(Runnable firstTask) {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   628
            setState(-1); // inhibit interrupts until runWorker
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   629
            this.firstTask = firstTask;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   630
            this.thread = getThreadFactory().newThread(this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   631
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   632
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   633
        /** Delegates main run loop to outer runWorker. */
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   634
        public void run() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   635
            runWorker(this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   636
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   637
90ce3da70b43 Initial load
duke
parents:
diff changeset
   638
        // Lock methods
90ce3da70b43 Initial load
duke
parents:
diff changeset
   639
        //
90ce3da70b43 Initial load
duke
parents:
diff changeset
   640
        // The value 0 represents the unlocked state.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   641
        // The value 1 represents the locked state.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   642
90ce3da70b43 Initial load
duke
parents:
diff changeset
   643
        protected boolean isHeldExclusively() {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   644
            return getState() != 0;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   645
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   646
90ce3da70b43 Initial load
duke
parents:
diff changeset
   647
        protected boolean tryAcquire(int unused) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   648
            if (compareAndSetState(0, 1)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   649
                setExclusiveOwnerThread(Thread.currentThread());
90ce3da70b43 Initial load
duke
parents:
diff changeset
   650
                return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   651
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   652
            return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   653
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   654
90ce3da70b43 Initial load
duke
parents:
diff changeset
   655
        protected boolean tryRelease(int unused) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   656
            setExclusiveOwnerThread(null);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   657
            setState(0);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   658
            return true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   659
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   660
90ce3da70b43 Initial load
duke
parents:
diff changeset
   661
        public void lock()        { acquire(1); }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   662
        public boolean tryLock()  { return tryAcquire(1); }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   663
        public void unlock()      { release(1); }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   664
        public boolean isLocked() { return isHeldExclusively(); }
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   665
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   666
        void interruptIfStarted() {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   667
            Thread t;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   668
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   669
                try {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   670
                    t.interrupt();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   671
                } catch (SecurityException ignore) {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   672
                }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   673
            }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   674
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   675
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   676
90ce3da70b43 Initial load
duke
parents:
diff changeset
   677
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   678
     * Methods for setting control state
90ce3da70b43 Initial load
duke
parents:
diff changeset
   679
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   680
90ce3da70b43 Initial load
duke
parents:
diff changeset
   681
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   682
     * Transitions runState to given target, or leaves it alone if
90ce3da70b43 Initial load
duke
parents:
diff changeset
   683
     * already at least the given target.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   684
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   685
     * @param targetState the desired state, either SHUTDOWN or STOP
90ce3da70b43 Initial load
duke
parents:
diff changeset
   686
     *        (but not TIDYING or TERMINATED -- use tryTerminate for that)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   687
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   688
    private void advanceRunState(int targetState) {
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   689
        // assert targetState == SHUTDOWN || targetState == STOP;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   690
        for (;;) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   691
            int c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   692
            if (runStateAtLeast(c, targetState) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   693
                ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   694
                break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   695
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   696
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   697
90ce3da70b43 Initial load
duke
parents:
diff changeset
   698
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   699
     * Transitions to TERMINATED state if either (SHUTDOWN and pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
   700
     * and queue empty) or (STOP and pool empty).  If otherwise
90ce3da70b43 Initial load
duke
parents:
diff changeset
   701
     * eligible to terminate but workerCount is nonzero, interrupts an
90ce3da70b43 Initial load
duke
parents:
diff changeset
   702
     * idle worker to ensure that shutdown signals propagate. This
90ce3da70b43 Initial load
duke
parents:
diff changeset
   703
     * method must be called following any action that might make
90ce3da70b43 Initial load
duke
parents:
diff changeset
   704
     * termination possible -- reducing worker count or removing tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
   705
     * from the queue during shutdown. The method is non-private to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   706
     * allow access from ScheduledThreadPoolExecutor.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   707
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   708
    final void tryTerminate() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   709
        for (;;) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   710
            int c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   711
            if (isRunning(c) ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
   712
                runStateAtLeast(c, TIDYING) ||
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   713
                (runStateLessThan(c, STOP) && ! workQueue.isEmpty()))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   714
                return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   715
            if (workerCountOf(c) != 0) { // Eligible to terminate
90ce3da70b43 Initial load
duke
parents:
diff changeset
   716
                interruptIdleWorkers(ONLY_ONE);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   717
                return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   718
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   719
90ce3da70b43 Initial load
duke
parents:
diff changeset
   720
            final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   721
            mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   722
            try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   723
                if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   724
                    try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   725
                        terminated();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   726
                    } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   727
                        ctl.set(ctlOf(TERMINATED, 0));
90ce3da70b43 Initial load
duke
parents:
diff changeset
   728
                        termination.signalAll();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   729
                    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   730
                    return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   731
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   732
            } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   733
                mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   734
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   735
            // else retry on failed CAS
90ce3da70b43 Initial load
duke
parents:
diff changeset
   736
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   737
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   738
90ce3da70b43 Initial load
duke
parents:
diff changeset
   739
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   740
     * Methods for controlling interrupts to worker threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   741
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   742
90ce3da70b43 Initial load
duke
parents:
diff changeset
   743
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   744
     * If there is a security manager, makes sure caller has
90ce3da70b43 Initial load
duke
parents:
diff changeset
   745
     * permission to shut down threads in general (see shutdownPerm).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   746
     * If this passes, additionally makes sure the caller is allowed
90ce3da70b43 Initial load
duke
parents:
diff changeset
   747
     * to interrupt each worker thread. This might not be true even if
90ce3da70b43 Initial load
duke
parents:
diff changeset
   748
     * first check passed, if the SecurityManager treats some threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
   749
     * specially.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   750
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   751
    private void checkShutdownAccess() {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   752
        // assert mainLock.isHeldByCurrentThread();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   753
        SecurityManager security = System.getSecurityManager();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   754
        if (security != null) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   755
            security.checkPermission(shutdownPerm);
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   756
            for (Worker w : workers)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   757
                security.checkAccess(w.thread);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   758
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   759
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   760
90ce3da70b43 Initial load
duke
parents:
diff changeset
   761
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   762
     * Interrupts all threads, even if active. Ignores SecurityExceptions
90ce3da70b43 Initial load
duke
parents:
diff changeset
   763
     * (in which case some threads may remain uninterrupted).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   764
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   765
    private void interruptWorkers() {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   766
        // assert mainLock.isHeldByCurrentThread();
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   767
        for (Worker w : workers)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   768
            w.interruptIfStarted();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   769
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   770
90ce3da70b43 Initial load
duke
parents:
diff changeset
   771
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   772
     * Interrupts threads that might be waiting for tasks (as
90ce3da70b43 Initial load
duke
parents:
diff changeset
   773
     * indicated by not being locked) so they can check for
90ce3da70b43 Initial load
duke
parents:
diff changeset
   774
     * termination or configuration changes. Ignores
90ce3da70b43 Initial load
duke
parents:
diff changeset
   775
     * SecurityExceptions (in which case some threads may remain
90ce3da70b43 Initial load
duke
parents:
diff changeset
   776
     * uninterrupted).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   777
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   778
     * @param onlyOne If true, interrupt at most one worker. This is
90ce3da70b43 Initial load
duke
parents:
diff changeset
   779
     * called only from tryTerminate when termination is otherwise
90ce3da70b43 Initial load
duke
parents:
diff changeset
   780
     * enabled but there are still other workers.  In this case, at
90ce3da70b43 Initial load
duke
parents:
diff changeset
   781
     * most one waiting worker is interrupted to propagate shutdown
90ce3da70b43 Initial load
duke
parents:
diff changeset
   782
     * signals in case all threads are currently waiting.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   783
     * Interrupting any arbitrary thread ensures that newly arriving
90ce3da70b43 Initial load
duke
parents:
diff changeset
   784
     * workers since shutdown began will also eventually exit.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   785
     * To guarantee eventual termination, it suffices to always
90ce3da70b43 Initial load
duke
parents:
diff changeset
   786
     * interrupt only one idle worker, but shutdown() interrupts all
90ce3da70b43 Initial load
duke
parents:
diff changeset
   787
     * idle workers so that redundant workers exit promptly, not
90ce3da70b43 Initial load
duke
parents:
diff changeset
   788
     * waiting for a straggler task to finish.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   789
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   790
    private void interruptIdleWorkers(boolean onlyOne) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   791
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   792
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   793
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   794
            for (Worker w : workers) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   795
                Thread t = w.thread;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   796
                if (!t.isInterrupted() && w.tryLock()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   797
                    try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   798
                        t.interrupt();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   799
                    } catch (SecurityException ignore) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   800
                    } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   801
                        w.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   802
                    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   803
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   804
                if (onlyOne)
90ce3da70b43 Initial load
duke
parents:
diff changeset
   805
                    break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   806
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   807
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   808
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   809
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   810
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   811
90ce3da70b43 Initial load
duke
parents:
diff changeset
   812
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   813
     * Common form of interruptIdleWorkers, to avoid having to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   814
     * remember what the boolean argument means.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   815
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   816
    private void interruptIdleWorkers() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   817
        interruptIdleWorkers(false);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   818
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   819
90ce3da70b43 Initial load
duke
parents:
diff changeset
   820
    private static final boolean ONLY_ONE = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   821
90ce3da70b43 Initial load
duke
parents:
diff changeset
   822
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   823
     * Misc utilities, most of which are also exported to
90ce3da70b43 Initial load
duke
parents:
diff changeset
   824
     * ScheduledThreadPoolExecutor
90ce3da70b43 Initial load
duke
parents:
diff changeset
   825
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   826
90ce3da70b43 Initial load
duke
parents:
diff changeset
   827
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   828
     * Invokes the rejected execution handler for the given command.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   829
     * Package-protected for use by ScheduledThreadPoolExecutor.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   830
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   831
    final void reject(Runnable command) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   832
        handler.rejectedExecution(command, this);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   833
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   834
90ce3da70b43 Initial load
duke
parents:
diff changeset
   835
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   836
     * Performs any further cleanup following run state transition on
90ce3da70b43 Initial load
duke
parents:
diff changeset
   837
     * invocation of shutdown.  A no-op here, but used by
90ce3da70b43 Initial load
duke
parents:
diff changeset
   838
     * ScheduledThreadPoolExecutor to cancel delayed tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   839
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   840
    void onShutdown() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   841
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   842
90ce3da70b43 Initial load
duke
parents:
diff changeset
   843
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   844
     * Drains the task queue into a new list, normally using
90ce3da70b43 Initial load
duke
parents:
diff changeset
   845
     * drainTo. But if the queue is a DelayQueue or any other kind of
90ce3da70b43 Initial load
duke
parents:
diff changeset
   846
     * queue for which poll or drainTo may fail to remove some
90ce3da70b43 Initial load
duke
parents:
diff changeset
   847
     * elements, it deletes them one by one.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   848
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   849
    private List<Runnable> drainQueue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   850
        BlockingQueue<Runnable> q = workQueue;
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
   851
        ArrayList<Runnable> taskList = new ArrayList<>();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   852
        q.drainTo(taskList);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   853
        if (!q.isEmpty()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   854
            for (Runnable r : q.toArray(new Runnable[0])) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   855
                if (q.remove(r))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   856
                    taskList.add(r);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   857
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   858
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   859
        return taskList;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   860
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   861
90ce3da70b43 Initial load
duke
parents:
diff changeset
   862
    /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
   863
     * Methods for creating, running and cleaning up after workers
90ce3da70b43 Initial load
duke
parents:
diff changeset
   864
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   865
90ce3da70b43 Initial load
duke
parents:
diff changeset
   866
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   867
     * Checks if a new worker can be added with respect to current
90ce3da70b43 Initial load
duke
parents:
diff changeset
   868
     * pool state and the given bound (either core or maximum). If so,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   869
     * the worker count is adjusted accordingly, and, if possible, a
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   870
     * new worker is created and started, running firstTask as its
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   871
     * first task. This method returns false if the pool is stopped or
90ce3da70b43 Initial load
duke
parents:
diff changeset
   872
     * eligible to shut down. It also returns false if the thread
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   873
     * factory fails to create a thread when asked.  If the thread
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   874
     * creation fails, either due to the thread factory returning
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   875
     * null, or due to an exception (typically OutOfMemoryError in
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   876
     * Thread.start()), we roll back cleanly.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   877
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   878
     * @param firstTask the task the new thread should run first (or
90ce3da70b43 Initial load
duke
parents:
diff changeset
   879
     * null if none). Workers are created with an initial first task
90ce3da70b43 Initial load
duke
parents:
diff changeset
   880
     * (in method execute()) to bypass queuing when there are fewer
90ce3da70b43 Initial load
duke
parents:
diff changeset
   881
     * than corePoolSize threads (in which case we always start one),
90ce3da70b43 Initial load
duke
parents:
diff changeset
   882
     * or when the queue is full (in which case we must bypass queue).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   883
     * Initially idle threads are usually created via
90ce3da70b43 Initial load
duke
parents:
diff changeset
   884
     * prestartCoreThread or to replace other dying workers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   885
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   886
     * @param core if true use corePoolSize as bound, else
90ce3da70b43 Initial load
duke
parents:
diff changeset
   887
     * maximumPoolSize. (A boolean indicator is used here rather than a
90ce3da70b43 Initial load
duke
parents:
diff changeset
   888
     * value to ensure reads of fresh values after checking other pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
   889
     * state).
90ce3da70b43 Initial load
duke
parents:
diff changeset
   890
     * @return true if successful
90ce3da70b43 Initial load
duke
parents:
diff changeset
   891
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   892
    private boolean addWorker(Runnable firstTask, boolean core) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   893
        retry:
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   894
        for (int c = ctl.get();;) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   895
            // Check if queue empty only if necessary.
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   896
            if (runStateAtLeast(c, SHUTDOWN)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   897
                && (runStateAtLeast(c, STOP)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   898
                    || firstTask != null
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   899
                    || workQueue.isEmpty()))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   900
                return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   901
90ce3da70b43 Initial load
duke
parents:
diff changeset
   902
            for (;;) {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   903
                if (workerCountOf(c)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   904
                    >= ((core ? corePoolSize : maximumPoolSize) & COUNT_MASK))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   905
                    return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   906
                if (compareAndIncrementWorkerCount(c))
90ce3da70b43 Initial load
duke
parents:
diff changeset
   907
                    break retry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   908
                c = ctl.get();  // Re-read ctl
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   909
                if (runStateAtLeast(c, SHUTDOWN))
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   910
                    continue retry;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   911
                // else CAS failed due to workerCount change; retry inner loop
90ce3da70b43 Initial load
duke
parents:
diff changeset
   912
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   913
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   914
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   915
        boolean workerStarted = false;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   916
        boolean workerAdded = false;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   917
        Worker w = null;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   918
        try {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   919
            w = new Worker(firstTask);
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   920
            final Thread t = w.thread;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   921
            if (t != null) {
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
   922
                final ReentrantLock mainLock = this.mainLock;
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   923
                mainLock.lock();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   924
                try {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   925
                    // Recheck while holding lock.
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   926
                    // Back out on ThreadFactory failure or if
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   927
                    // shut down before lock acquired.
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   928
                    int c = ctl.get();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   929
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   930
                    if (isRunning(c) ||
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
   931
                        (runStateLessThan(c, STOP) && firstTask == null)) {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   932
                        if (t.isAlive()) // precheck that t is startable
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   933
                            throw new IllegalThreadStateException();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   934
                        workers.add(w);
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   935
                        int s = workers.size();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   936
                        if (s > largestPoolSize)
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   937
                            largestPoolSize = s;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   938
                        workerAdded = true;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   939
                    }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   940
                } finally {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   941
                    mainLock.unlock();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   942
                }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   943
                if (workerAdded) {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   944
                    t.start();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   945
                    workerStarted = true;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   946
                }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   947
            }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   948
        } finally {
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   949
            if (! workerStarted)
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   950
                addWorkerFailed(w);
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   951
        }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   952
        return workerStarted;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   953
    }
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   954
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   955
    /**
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   956
     * Rolls back the worker thread creation.
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   957
     * - removes worker from workers, if present
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   958
     * - decrements worker count
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   959
     * - rechecks for termination, in case the existence of this
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   960
     *   worker was holding up termination
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   961
     */
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   962
    private void addWorkerFailed(Worker w) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   963
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   964
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   965
        try {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   966
            if (w != null)
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   967
                workers.remove(w);
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   968
            decrementWorkerCount();
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
   969
            tryTerminate();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
   970
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   971
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   972
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   973
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
   974
90ce3da70b43 Initial load
duke
parents:
diff changeset
   975
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
   976
     * Performs cleanup and bookkeeping for a dying worker. Called
90ce3da70b43 Initial load
duke
parents:
diff changeset
   977
     * only from worker threads. Unless completedAbruptly is set,
90ce3da70b43 Initial load
duke
parents:
diff changeset
   978
     * assumes that workerCount has already been adjusted to account
90ce3da70b43 Initial load
duke
parents:
diff changeset
   979
     * for exit.  This method removes thread from worker set, and
90ce3da70b43 Initial load
duke
parents:
diff changeset
   980
     * possibly terminates the pool or replaces the worker if either
90ce3da70b43 Initial load
duke
parents:
diff changeset
   981
     * it exited due to user task exception or if fewer than
90ce3da70b43 Initial load
duke
parents:
diff changeset
   982
     * corePoolSize workers are running or queue is non-empty but
90ce3da70b43 Initial load
duke
parents:
diff changeset
   983
     * there are no workers.
90ce3da70b43 Initial load
duke
parents:
diff changeset
   984
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
   985
     * @param w the worker
90ce3da70b43 Initial load
duke
parents:
diff changeset
   986
     * @param completedAbruptly if the worker died due to user exception
90ce3da70b43 Initial load
duke
parents:
diff changeset
   987
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
   988
    private void processWorkerExit(Worker w, boolean completedAbruptly) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   989
        if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
90ce3da70b43 Initial load
duke
parents:
diff changeset
   990
            decrementWorkerCount();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   991
90ce3da70b43 Initial load
duke
parents:
diff changeset
   992
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   993
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   994
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   995
            completedTaskCount += w.completedTasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
   996
            workers.remove(w);
90ce3da70b43 Initial load
duke
parents:
diff changeset
   997
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
   998
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
   999
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1000
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1001
        tryTerminate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1002
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1003
        int c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1004
        if (runStateLessThan(c, STOP)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1005
            if (!completedAbruptly) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1006
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1007
                if (min == 0 && ! workQueue.isEmpty())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1008
                    min = 1;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1009
                if (workerCountOf(c) >= min)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1010
                    return; // replacement not needed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1011
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1012
            addWorker(null, false);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1013
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1014
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1015
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1016
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1017
     * Performs blocking or timed wait for a task, depending on
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1018
     * current configuration settings, or returns null if this worker
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1019
     * must exit because of any of:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1020
     * 1. There are more than maximumPoolSize workers (due to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1021
     *    a call to setMaximumPoolSize).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1022
     * 2. The pool is stopped.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1023
     * 3. The pool is shutdown and the queue is empty.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1024
     * 4. This worker timed out waiting for a task, and timed-out
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1025
     *    workers are subject to termination (that is,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1026
     *    {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1027
     *    both before and after the timed wait, and if the queue is
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1028
     *    non-empty, this worker is not the last thread in the pool.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1029
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1030
     * @return task, or null if the worker must exit, in which case
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1031
     *         workerCount is decremented
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1032
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1033
    private Runnable getTask() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1034
        boolean timedOut = false; // Did the last poll() time out?
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1035
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1036
        for (;;) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1037
            int c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1038
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1039
            // Check if queue empty only if necessary.
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1040
            if (runStateAtLeast(c, SHUTDOWN)
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1041
                && (runStateAtLeast(c, STOP) || workQueue.isEmpty())) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1042
                decrementWorkerCount();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1043
                return null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1044
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1045
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1046
            int wc = workerCountOf(c);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1047
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1048
            // Are workers subject to culling?
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1049
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1050
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1051
            if ((wc > maximumPoolSize || (timed && timedOut))
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1052
                && (wc > 1 || workQueue.isEmpty())) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1053
                if (compareAndDecrementWorkerCount(c))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1054
                    return null;
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1055
                continue;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1056
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1057
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1058
            try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1059
                Runnable r = timed ?
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1060
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1061
                    workQueue.take();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1062
                if (r != null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1063
                    return r;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1064
                timedOut = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1065
            } catch (InterruptedException retry) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1066
                timedOut = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1067
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1068
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1069
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1070
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1071
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1072
     * Main worker run loop.  Repeatedly gets tasks from queue and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1073
     * executes them, while coping with a number of issues:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1074
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1075
     * 1. We may start out with an initial task, in which case we
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1076
     * don't need to get the first one. Otherwise, as long as pool is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1077
     * running, we get tasks from getTask. If it returns null then the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1078
     * worker exits due to changed pool state or configuration
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1079
     * parameters.  Other exits result from exception throws in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1080
     * external code, in which case completedAbruptly holds, which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1081
     * usually leads processWorkerExit to replace this thread.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1082
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1083
     * 2. Before running any task, the lock is acquired to prevent
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1084
     * other pool interrupts while the task is executing, and then we
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1085
     * ensure that unless pool is stopping, this thread does not have
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1086
     * its interrupt set.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1087
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1088
     * 3. Each task run is preceded by a call to beforeExecute, which
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1089
     * might throw an exception, in which case we cause thread to die
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1090
     * (breaking loop with completedAbruptly true) without processing
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1091
     * the task.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1092
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1093
     * 4. Assuming beforeExecute completes normally, we run the task,
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1094
     * gathering any of its thrown exceptions to send to afterExecute.
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1095
     * We separately handle RuntimeException, Error (both of which the
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1096
     * specs guarantee that we trap) and arbitrary Throwables.
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1097
     * Because we cannot rethrow Throwables within Runnable.run, we
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1098
     * wrap them within Errors on the way out (to the thread's
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1099
     * UncaughtExceptionHandler).  Any thrown exception also
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1100
     * conservatively causes thread to die.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1101
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1102
     * 5. After task.run completes, we call afterExecute, which may
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1103
     * also throw an exception, which will also cause thread to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1104
     * die. According to JLS Sec 14.20, this exception is the one that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1105
     * will be in effect even if task.run throws.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1106
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1107
     * The net effect of the exception mechanics is that afterExecute
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1108
     * and the thread's UncaughtExceptionHandler have as accurate
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1109
     * information as we can provide about any problems encountered by
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1110
     * user code.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1111
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1112
     * @param w the worker
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1113
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1114
    final void runWorker(Worker w) {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1115
        Thread wt = Thread.currentThread();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1116
        Runnable task = w.firstTask;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1117
        w.firstTask = null;
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1118
        w.unlock(); // allow interrupts
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1119
        boolean completedAbruptly = true;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1120
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1121
            while (task != null || (task = getTask()) != null) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1122
                w.lock();
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1123
                // If pool is stopping, ensure thread is interrupted;
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1124
                // if not, ensure thread is not interrupted.  This
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1125
                // requires a recheck in second case to deal with
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1126
                // shutdownNow race while clearing interrupt
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1127
                if ((runStateAtLeast(ctl.get(), STOP) ||
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1128
                     (Thread.interrupted() &&
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1129
                      runStateAtLeast(ctl.get(), STOP))) &&
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1130
                    !wt.isInterrupted())
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1131
                    wt.interrupt();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1132
                try {
16079
7252530399e2 6776941: Improve thread pool shutdown
dholmes
parents: 10609
diff changeset
  1133
                    beforeExecute(wt, task);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1134
                    try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1135
                        task.run();
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1136
                        afterExecute(task, null);
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1137
                    } catch (Throwable ex) {
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1138
                        afterExecute(task, ex);
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1139
                        throw ex;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1140
                    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1141
                } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1142
                    task = null;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1143
                    w.completedTasks++;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1144
                    w.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1145
                }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1146
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1147
            completedAbruptly = false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1148
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1149
            processWorkerExit(w, completedAbruptly);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1150
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1151
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1152
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1153
    // Public constructors and methods
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1154
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1155
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1156
     * Creates a new {@code ThreadPoolExecutor} with the given initial
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1157
     * parameters, the default thread factory and the default rejected
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1158
     * execution handler.
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1159
     *
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1160
     * <p>It may be more convenient to use one of the {@link Executors}
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1161
     * factory methods instead of this general purpose constructor.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1162
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1163
     * @param corePoolSize the number of threads to keep in the pool, even
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1164
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1165
     * @param maximumPoolSize the maximum number of threads to allow in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1166
     *        pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1167
     * @param keepAliveTime when the number of threads is greater than
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1168
     *        the core, this is the maximum time that excess idle threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1169
     *        will wait for new tasks before terminating.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1170
     * @param unit the time unit for the {@code keepAliveTime} argument
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1171
     * @param workQueue the queue to use for holding tasks before they are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1172
     *        executed.  This queue will hold only the {@code Runnable}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1173
     *        tasks submitted by the {@code execute} method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1174
     * @throws IllegalArgumentException if one of the following holds:<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1175
     *         {@code corePoolSize < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1176
     *         {@code keepAliveTime < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1177
     *         {@code maximumPoolSize <= 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1178
     *         {@code maximumPoolSize < corePoolSize}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1179
     * @throws NullPointerException if {@code workQueue} is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1180
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1181
    public ThreadPoolExecutor(int corePoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1182
                              int maximumPoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1183
                              long keepAliveTime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1184
                              TimeUnit unit,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1185
                              BlockingQueue<Runnable> workQueue) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1186
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1187
             Executors.defaultThreadFactory(), defaultHandler);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1188
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1189
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1190
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1191
     * Creates a new {@code ThreadPoolExecutor} with the given initial
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1192
     * parameters and {@linkplain ThreadPoolExecutor.AbortPolicy
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1193
     * default rejected execution handler}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1194
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1195
     * @param corePoolSize the number of threads to keep in the pool, even
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1196
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1197
     * @param maximumPoolSize the maximum number of threads to allow in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1198
     *        pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1199
     * @param keepAliveTime when the number of threads is greater than
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1200
     *        the core, this is the maximum time that excess idle threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1201
     *        will wait for new tasks before terminating.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1202
     * @param unit the time unit for the {@code keepAliveTime} argument
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1203
     * @param workQueue the queue to use for holding tasks before they are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1204
     *        executed.  This queue will hold only the {@code Runnable}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1205
     *        tasks submitted by the {@code execute} method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1206
     * @param threadFactory the factory to use when the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1207
     *        creates a new thread
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1208
     * @throws IllegalArgumentException if one of the following holds:<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1209
     *         {@code corePoolSize < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1210
     *         {@code keepAliveTime < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1211
     *         {@code maximumPoolSize <= 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1212
     *         {@code maximumPoolSize < corePoolSize}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1213
     * @throws NullPointerException if {@code workQueue}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1214
     *         or {@code threadFactory} is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1215
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1216
    public ThreadPoolExecutor(int corePoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1217
                              int maximumPoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1218
                              long keepAliveTime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1219
                              TimeUnit unit,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1220
                              BlockingQueue<Runnable> workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1221
                              ThreadFactory threadFactory) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1222
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1223
             threadFactory, defaultHandler);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1224
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1225
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1226
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1227
     * Creates a new {@code ThreadPoolExecutor} with the given initial
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1228
     * parameters and
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1229
     * {@linkplain Executors#defaultThreadFactory default thread factory}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1230
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1231
     * @param corePoolSize the number of threads to keep in the pool, even
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1232
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1233
     * @param maximumPoolSize the maximum number of threads to allow in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1234
     *        pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1235
     * @param keepAliveTime when the number of threads is greater than
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1236
     *        the core, this is the maximum time that excess idle threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1237
     *        will wait for new tasks before terminating.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1238
     * @param unit the time unit for the {@code keepAliveTime} argument
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1239
     * @param workQueue the queue to use for holding tasks before they are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1240
     *        executed.  This queue will hold only the {@code Runnable}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1241
     *        tasks submitted by the {@code execute} method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1242
     * @param handler the handler to use when execution is blocked
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1243
     *        because the thread bounds and queue capacities are reached
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1244
     * @throws IllegalArgumentException if one of the following holds:<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1245
     *         {@code corePoolSize < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1246
     *         {@code keepAliveTime < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1247
     *         {@code maximumPoolSize <= 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1248
     *         {@code maximumPoolSize < corePoolSize}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1249
     * @throws NullPointerException if {@code workQueue}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1250
     *         or {@code handler} is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1251
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1252
    public ThreadPoolExecutor(int corePoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1253
                              int maximumPoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1254
                              long keepAliveTime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1255
                              TimeUnit unit,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1256
                              BlockingQueue<Runnable> workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1257
                              RejectedExecutionHandler handler) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1258
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1259
             Executors.defaultThreadFactory(), handler);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1260
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1261
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1262
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1263
     * Creates a new {@code ThreadPoolExecutor} with the given initial
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1264
     * parameters.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1265
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1266
     * @param corePoolSize the number of threads to keep in the pool, even
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1267
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1268
     * @param maximumPoolSize the maximum number of threads to allow in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1269
     *        pool
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1270
     * @param keepAliveTime when the number of threads is greater than
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1271
     *        the core, this is the maximum time that excess idle threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1272
     *        will wait for new tasks before terminating.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1273
     * @param unit the time unit for the {@code keepAliveTime} argument
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1274
     * @param workQueue the queue to use for holding tasks before they are
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1275
     *        executed.  This queue will hold only the {@code Runnable}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1276
     *        tasks submitted by the {@code execute} method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1277
     * @param threadFactory the factory to use when the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1278
     *        creates a new thread
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1279
     * @param handler the handler to use when execution is blocked
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1280
     *        because the thread bounds and queue capacities are reached
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1281
     * @throws IllegalArgumentException if one of the following holds:<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1282
     *         {@code corePoolSize < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1283
     *         {@code keepAliveTime < 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1284
     *         {@code maximumPoolSize <= 0}<br>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1285
     *         {@code maximumPoolSize < corePoolSize}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1286
     * @throws NullPointerException if {@code workQueue}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1287
     *         or {@code threadFactory} or {@code handler} is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1288
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1289
    public ThreadPoolExecutor(int corePoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1290
                              int maximumPoolSize,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1291
                              long keepAliveTime,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1292
                              TimeUnit unit,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1293
                              BlockingQueue<Runnable> workQueue,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1294
                              ThreadFactory threadFactory,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1295
                              RejectedExecutionHandler handler) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1296
        if (corePoolSize < 0 ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1297
            maximumPoolSize <= 0 ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1298
            maximumPoolSize < corePoolSize ||
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1299
            keepAliveTime < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1300
            throw new IllegalArgumentException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1301
        if (workQueue == null || threadFactory == null || handler == null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1302
            throw new NullPointerException();
46146
b3e220a04d3f 8185099: Miscellaneous changes imported from jsr166 CVS 2017-08
dl
parents: 46041
diff changeset
  1303
        this.acc = (System.getSecurityManager() == null)
b3e220a04d3f 8185099: Miscellaneous changes imported from jsr166 CVS 2017-08
dl
parents: 46041
diff changeset
  1304
            ? null
b3e220a04d3f 8185099: Miscellaneous changes imported from jsr166 CVS 2017-08
dl
parents: 46041
diff changeset
  1305
            : AccessController.getContext();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1306
        this.corePoolSize = corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1307
        this.maximumPoolSize = maximumPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1308
        this.workQueue = workQueue;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1309
        this.keepAliveTime = unit.toNanos(keepAliveTime);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1310
        this.threadFactory = threadFactory;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1311
        this.handler = handler;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1312
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1313
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1314
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1315
     * Executes the given task sometime in the future.  The task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1316
     * may execute in a new thread or in an existing pooled thread.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1317
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1318
     * If the task cannot be submitted for execution, either because this
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1319
     * executor has been shutdown or because its capacity has been reached,
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1320
     * the task is handled by the current {@link RejectedExecutionHandler}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1321
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1322
     * @param command the task to execute
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1323
     * @throws RejectedExecutionException at discretion of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1324
     *         {@code RejectedExecutionHandler}, if the task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1325
     *         cannot be accepted for execution
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1326
     * @throws NullPointerException if {@code command} is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1327
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1328
    public void execute(Runnable command) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1329
        if (command == null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1330
            throw new NullPointerException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1331
        /*
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1332
         * Proceed in 3 steps:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1333
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1334
         * 1. If fewer than corePoolSize threads are running, try to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1335
         * start a new thread with the given command as its first
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1336
         * task.  The call to addWorker atomically checks runState and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1337
         * workerCount, and so prevents false alarms that would add
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1338
         * threads when it shouldn't, by returning false.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1339
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1340
         * 2. If a task can be successfully queued, then we still need
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1341
         * to double-check whether we should have added a thread
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1342
         * (because existing ones died since last checking) or that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1343
         * the pool shut down since entry into this method. So we
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1344
         * recheck state and if necessary roll back the enqueuing if
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1345
         * stopped, or start a new thread if there are none.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1346
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1347
         * 3. If we cannot queue task, then we try to add a new
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1348
         * thread.  If it fails, we know we are shut down or saturated
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1349
         * and so reject the task.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1350
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1351
        int c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1352
        if (workerCountOf(c) < corePoolSize) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1353
            if (addWorker(command, true))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1354
                return;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1355
            c = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1356
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1357
        if (isRunning(c) && workQueue.offer(command)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1358
            int recheck = ctl.get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1359
            if (! isRunning(recheck) && remove(command))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1360
                reject(command);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1361
            else if (workerCountOf(recheck) == 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1362
                addWorker(null, false);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1363
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1364
        else if (!addWorker(command, false))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1365
            reject(command);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1366
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1367
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1368
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1369
     * Initiates an orderly shutdown in which previously submitted
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1370
     * tasks are executed, but no new tasks will be accepted.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1371
     * Invocation has no additional effect if already shut down.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1372
     *
61
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1373
     * <p>This method does not wait for previously submitted tasks to
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1374
     * complete execution.  Use {@link #awaitTermination awaitTermination}
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1375
     * to do that.
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1376
     *
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1377
     * @throws SecurityException {@inheritDoc}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1378
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1379
    public void shutdown() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1380
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1381
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1382
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1383
            checkShutdownAccess();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1384
            advanceRunState(SHUTDOWN);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1385
            interruptIdleWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1386
            onShutdown(); // hook for ScheduledThreadPoolExecutor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1387
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1388
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1389
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1390
        tryTerminate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1391
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1392
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1393
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1394
     * Attempts to stop all actively executing tasks, halts the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1395
     * processing of waiting tasks, and returns a list of the tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1396
     * that were awaiting execution. These tasks are drained (removed)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1397
     * from the task queue upon return from this method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1398
     *
61
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1399
     * <p>This method does not wait for actively executing tasks to
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1400
     * terminate.  Use {@link #awaitTermination awaitTermination} to
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1401
     * do that.
5691b03db1ea 6620549: ExecutorService#shutdown should clearly state that it does not block
martin
parents: 2
diff changeset
  1402
     *
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1403
     * <p>There are no guarantees beyond best-effort attempts to stop
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1404
     * processing actively executing tasks.  This implementation
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1405
     * interrupts tasks via {@link Thread#interrupt}; any task that
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1406
     * fails to respond to interrupts may never terminate.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1407
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1408
     * @throws SecurityException {@inheritDoc}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1409
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1410
    public List<Runnable> shutdownNow() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1411
        List<Runnable> tasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1412
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1413
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1414
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1415
            checkShutdownAccess();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1416
            advanceRunState(STOP);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1417
            interruptWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1418
            tasks = drainQueue();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1419
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1420
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1421
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1422
        tryTerminate();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1423
        return tasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1424
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1425
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1426
    public boolean isShutdown() {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1427
        return runStateAtLeast(ctl.get(), SHUTDOWN);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1428
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1429
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1430
    /** Used by ScheduledThreadPoolExecutor. */
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1431
    boolean isStopped() {
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1432
        return runStateAtLeast(ctl.get(), STOP);
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1433
    }
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  1434
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1435
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1436
     * Returns true if this executor is in the process of terminating
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1437
     * after {@link #shutdown} or {@link #shutdownNow} but has not
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1438
     * completely terminated.  This method may be useful for
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1439
     * debugging. A return of {@code true} reported a sufficient
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1440
     * period after shutdown may indicate that submitted tasks have
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1441
     * ignored or suppressed interruption, causing this executor not
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1442
     * to properly terminate.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1443
     *
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1444
     * @return {@code true} if terminating but not yet terminated
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1445
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1446
    public boolean isTerminating() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1447
        int c = ctl.get();
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1448
        return runStateAtLeast(c, SHUTDOWN) && runStateLessThan(c, TERMINATED);
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1449
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1450
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1451
    public boolean isTerminated() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1452
        return runStateAtLeast(ctl.get(), TERMINATED);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1453
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1454
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1455
    public boolean awaitTermination(long timeout, TimeUnit unit)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1456
        throws InterruptedException {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1457
        long nanos = unit.toNanos(timeout);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1458
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1459
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1460
        try {
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1461
            while (runStateLessThan(ctl.get(), TERMINATED)) {
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1462
                if (nanos <= 0L)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1463
                    return false;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1464
                nanos = termination.awaitNanos(nanos);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1465
            }
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1466
            return true;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1467
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1468
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1469
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1470
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1471
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1472
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1473
     * Invokes {@code shutdown} when this executor is no longer
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1474
     * referenced and it has no threads.
44534
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1475
     *
45978
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1476
     * <p>This method is invoked with privileges that are restricted by
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1477
     * the security context of the caller that invokes the constructor.
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1478
     *
44534
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1479
     * @deprecated The {@code finalize} method has been deprecated.
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1480
     *     Subclasses that override {@code finalize} in order to perform cleanup
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1481
     *     should be modified to use alternative cleanup mechanisms and
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1482
     *     to remove the overriding {@code finalize} method.
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1483
     *     When overriding the {@code finalize} method, its implementation must explicitly
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1484
     *     ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1485
     *     See the specification for {@link Object#finalize()} for further
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1486
     *     information about migration options.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1487
     */
44534
a076dffbc2c1 8165641: Deprecate Object.finalize
rriggs
parents: 40817
diff changeset
  1488
    @Deprecated(since="9")
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1489
    protected void finalize() {
45978
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1490
        SecurityManager sm = System.getSecurityManager();
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1491
        if (sm == null || acc == null) {
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1492
            shutdown();
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1493
        } else {
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1494
            PrivilegedAction<Void> pa = () -> { shutdown(); return null; };
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1495
            AccessController.doPrivileged(pa, acc);
882d720b3edf 8172204: Better Thread Pool execution
chegar
parents: 44534
diff changeset
  1496
        }
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1497
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1498
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1499
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1500
     * Sets the thread factory used to create new threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1501
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1502
     * @param threadFactory the new thread factory
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1503
     * @throws NullPointerException if threadFactory is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1504
     * @see #getThreadFactory
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1505
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1506
    public void setThreadFactory(ThreadFactory threadFactory) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1507
        if (threadFactory == null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1508
            throw new NullPointerException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1509
        this.threadFactory = threadFactory;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1510
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1511
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1512
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1513
     * Returns the thread factory used to create new threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1514
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1515
     * @return the current thread factory
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1516
     * @see #setThreadFactory(ThreadFactory)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1517
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1518
    public ThreadFactory getThreadFactory() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1519
        return threadFactory;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1520
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1521
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1522
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1523
     * Sets a new handler for unexecutable tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1524
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1525
     * @param handler the new handler
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1526
     * @throws NullPointerException if handler is null
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1527
     * @see #getRejectedExecutionHandler
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1528
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1529
    public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1530
        if (handler == null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1531
            throw new NullPointerException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1532
        this.handler = handler;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1533
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1534
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1535
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1536
     * Returns the current handler for unexecutable tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1537
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1538
     * @return the current handler
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1539
     * @see #setRejectedExecutionHandler(RejectedExecutionHandler)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1540
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1541
    public RejectedExecutionHandler getRejectedExecutionHandler() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1542
        return handler;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1543
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1544
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1545
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1546
     * Sets the core number of threads.  This overrides any value set
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1547
     * in the constructor.  If the new value is smaller than the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1548
     * current value, excess existing threads will be terminated when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1549
     * they next become idle.  If larger, new threads will, if needed,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1550
     * be started to execute any queued tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1551
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1552
     * @param corePoolSize the new core size
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1553
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
24376
ad2f268e4a25 7153400: ThreadPoolExecutor's setCorePoolSize method allows corePoolSize > maxPoolSize
chegar
parents: 18790
diff changeset
  1554
     *         or {@code corePoolSize} is greater than the {@linkplain
ad2f268e4a25 7153400: ThreadPoolExecutor's setCorePoolSize method allows corePoolSize > maxPoolSize
chegar
parents: 18790
diff changeset
  1555
     *         #getMaximumPoolSize() maximum pool size}
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1556
     * @see #getCorePoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1557
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1558
    public void setCorePoolSize(int corePoolSize) {
24376
ad2f268e4a25 7153400: ThreadPoolExecutor's setCorePoolSize method allows corePoolSize > maxPoolSize
chegar
parents: 18790
diff changeset
  1559
        if (corePoolSize < 0 || maximumPoolSize < corePoolSize)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1560
            throw new IllegalArgumentException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1561
        int delta = corePoolSize - this.corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1562
        this.corePoolSize = corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1563
        if (workerCountOf(ctl.get()) > corePoolSize)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1564
            interruptIdleWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1565
        else if (delta > 0) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1566
            // We don't really know how many new threads are "needed".
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1567
            // As a heuristic, prestart enough new workers (up to new
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1568
            // core size) to handle the current number of tasks in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1569
            // queue, but stop if queue becomes empty while doing so.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1570
            int k = Math.min(delta, workQueue.size());
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1571
            while (k-- > 0 && addWorker(null, true)) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1572
                if (workQueue.isEmpty())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1573
                    break;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1574
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1575
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1576
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1577
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1578
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1579
     * Returns the core number of threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1580
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1581
     * @return the core number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1582
     * @see #setCorePoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1583
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1584
    public int getCorePoolSize() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1585
        return corePoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1586
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1587
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1588
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1589
     * Starts a core thread, causing it to idly wait for work. This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1590
     * overrides the default policy of starting core threads only when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1591
     * new tasks are executed. This method will return {@code false}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1592
     * if all core threads have already been started.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1593
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1594
     * @return {@code true} if a thread was started
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1595
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1596
    public boolean prestartCoreThread() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1597
        return workerCountOf(ctl.get()) < corePoolSize &&
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1598
            addWorker(null, true);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1599
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1600
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1601
    /**
10609
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1602
     * Same as prestartCoreThread except arranges that at least one
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1603
     * thread is started even if corePoolSize is 0.
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1604
     */
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1605
    void ensurePrestart() {
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1606
        int wc = workerCountOf(ctl.get());
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1607
        if (wc < corePoolSize)
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1608
            addWorker(null, true);
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1609
        else if (wc == 0)
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1610
            addWorker(null, false);
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1611
    }
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1612
0caee7f44e7b 7091003: ScheduledExecutorService never executes Runnable with corePoolSize of zero
dl
parents: 9242
diff changeset
  1613
    /**
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1614
     * Starts all core threads, causing them to idly wait for work. This
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1615
     * overrides the default policy of starting core threads only when
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1616
     * new tasks are executed.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1617
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1618
     * @return the number of threads started
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1619
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1620
    public int prestartAllCoreThreads() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1621
        int n = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1622
        while (addWorker(null, true))
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1623
            ++n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1624
        return n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1625
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1626
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1627
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1628
     * Returns true if this pool allows core threads to time out and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1629
     * terminate if no tasks arrive within the keepAlive time, being
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1630
     * replaced if needed when new tasks arrive. When true, the same
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1631
     * keep-alive policy applying to non-core threads applies also to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1632
     * core threads. When false (the default), core threads are never
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1633
     * terminated due to lack of incoming tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1634
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1635
     * @return {@code true} if core threads are allowed to time out,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1636
     *         else {@code false}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1637
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1638
     * @since 1.6
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1639
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1640
    public boolean allowsCoreThreadTimeOut() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1641
        return allowCoreThreadTimeOut;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1642
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1643
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1644
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1645
     * Sets the policy governing whether core threads may time out and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1646
     * terminate if no tasks arrive within the keep-alive time, being
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1647
     * replaced if needed when new tasks arrive. When false, core
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1648
     * threads are never terminated due to lack of incoming
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1649
     * tasks. When true, the same keep-alive policy applying to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1650
     * non-core threads applies also to core threads. To avoid
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1651
     * continual thread replacement, the keep-alive time must be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1652
     * greater than zero when setting {@code true}. This method
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1653
     * should in general be called before the pool is actively used.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1654
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1655
     * @param value {@code true} if should time out, else {@code false}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1656
     * @throws IllegalArgumentException if value is {@code true}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1657
     *         and the current keep-alive time is not greater than zero
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1658
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1659
     * @since 1.6
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1660
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1661
    public void allowCoreThreadTimeOut(boolean value) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1662
        if (value && keepAliveTime <= 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1663
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1664
        if (value != allowCoreThreadTimeOut) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1665
            allowCoreThreadTimeOut = value;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1666
            if (value)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1667
                interruptIdleWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1668
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1669
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1670
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1671
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1672
     * Sets the maximum allowed number of threads. This overrides any
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1673
     * value set in the constructor. If the new value is smaller than
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1674
     * the current value, excess existing threads will be
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1675
     * terminated when they next become idle.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1676
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1677
     * @param maximumPoolSize the new maximum
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1678
     * @throws IllegalArgumentException if the new maximum is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1679
     *         less than or equal to zero, or
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1680
     *         less than the {@linkplain #getCorePoolSize core pool size}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1681
     * @see #getMaximumPoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1682
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1683
    public void setMaximumPoolSize(int maximumPoolSize) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1684
        if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1685
            throw new IllegalArgumentException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1686
        this.maximumPoolSize = maximumPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1687
        if (workerCountOf(ctl.get()) > maximumPoolSize)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1688
            interruptIdleWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1689
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1690
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1691
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1692
     * Returns the maximum allowed number of threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1693
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1694
     * @return the maximum allowed number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1695
     * @see #setMaximumPoolSize
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1696
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1697
    public int getMaximumPoolSize() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1698
        return maximumPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1699
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1700
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1701
    /**
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1702
     * Sets the thread keep-alive time, which is the amount of time
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1703
     * that threads may remain idle before being terminated.
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1704
     * Threads that wait this amount of time without processing a
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1705
     * task will be terminated if there are more than the core
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1706
     * number of threads currently in the pool, or if this pool
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1707
     * {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}.
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1708
     * This overrides any value set in the constructor.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1709
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1710
     * @param time the time to wait.  A time value of zero will cause
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1711
     *        excess threads to terminate immediately after executing tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1712
     * @param unit the time unit of the {@code time} argument
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1713
     * @throws IllegalArgumentException if {@code time} less than zero or
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1714
     *         if {@code time} is zero and {@code allowsCoreThreadTimeOut}
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1715
     * @see #getKeepAliveTime(TimeUnit)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1716
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1717
    public void setKeepAliveTime(long time, TimeUnit unit) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1718
        if (time < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1719
            throw new IllegalArgumentException();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1720
        if (time == 0 && allowsCoreThreadTimeOut())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1721
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1722
        long keepAliveTime = unit.toNanos(time);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1723
        long delta = keepAliveTime - this.keepAliveTime;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1724
        this.keepAliveTime = keepAliveTime;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1725
        if (delta < 0)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1726
            interruptIdleWorkers();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1727
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1728
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1729
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1730
     * Returns the thread keep-alive time, which is the amount of time
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1731
     * that threads may remain idle before being terminated.
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1732
     * Threads that wait this amount of time without processing a
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1733
     * task will be terminated if there are more than the core
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1734
     * number of threads currently in the pool, or if this pool
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1735
     * {@linkplain #allowsCoreThreadTimeOut() allows core thread timeout}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1736
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1737
     * @param unit the desired time unit of the result
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1738
     * @return the time limit
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1739
     * @see #setKeepAliveTime(long, TimeUnit)
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1740
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1741
    public long getKeepAliveTime(TimeUnit unit) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1742
        return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1743
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1744
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1745
    /* User-level queue utilities */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1746
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1747
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1748
     * Returns the task queue used by this executor. Access to the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1749
     * task queue is intended primarily for debugging and monitoring.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1750
     * This queue may be in active use.  Retrieving the task queue
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1751
     * does not prevent queued tasks from executing.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1752
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1753
     * @return the task queue
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1754
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1755
    public BlockingQueue<Runnable> getQueue() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1756
        return workQueue;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1757
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1758
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1759
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1760
     * Removes this task from the executor's internal queue if it is
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1761
     * present, thus causing it not to be run if it has not already
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1762
     * started.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1763
     *
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1764
     * <p>This method may be useful as one part of a cancellation
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1765
     * scheme.  It may fail to remove tasks that have been converted
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1766
     * into other forms before being placed on the internal queue.
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1767
     * For example, a task entered using {@code submit} might be
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1768
     * converted into a form that maintains {@code Future} status.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1769
     * However, in such cases, method {@link #purge} may be used to
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1770
     * remove those Futures that have been cancelled.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1771
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1772
     * @param task the task to remove
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  1773
     * @return {@code true} if the task was removed
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1774
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1775
    public boolean remove(Runnable task) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1776
        boolean removed = workQueue.remove(task);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1777
        tryTerminate(); // In case SHUTDOWN and now empty
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1778
        return removed;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1779
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1780
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1781
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1782
     * Tries to remove from the work queue all {@link Future}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1783
     * tasks that have been cancelled. This method can be useful as a
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1784
     * storage reclamation operation, that has no other impact on
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1785
     * functionality. Cancelled tasks are never executed, but may
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1786
     * accumulate in work queues until worker threads can actively
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1787
     * remove them. Invoking this method instead tries to remove them now.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1788
     * However, this method may fail to remove tasks in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1789
     * the presence of interference by other threads.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1790
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1791
    public void purge() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1792
        final BlockingQueue<Runnable> q = workQueue;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1793
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1794
            Iterator<Runnable> it = q.iterator();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1795
            while (it.hasNext()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1796
                Runnable r = it.next();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1797
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1798
                    it.remove();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1799
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1800
        } catch (ConcurrentModificationException fallThrough) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1801
            // Take slow path if we encounter interference during traversal.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1802
            // Make copy for traversal and call remove for cancelled entries.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1803
            // The slow path is more likely to be O(N*N).
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1804
            for (Object r : q.toArray())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1805
                if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1806
                    q.remove(r);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1807
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1808
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1809
        tryTerminate(); // In case SHUTDOWN and now empty
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1810
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1811
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1812
    /* Statistics */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1813
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1814
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1815
     * Returns the current number of threads in the pool.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1816
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1817
     * @return the number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1818
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1819
    public int getPoolSize() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1820
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1821
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1822
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1823
            // Remove rare and surprising possibility of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1824
            // isTerminated() && getPoolSize() > 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1825
            return runStateAtLeast(ctl.get(), TIDYING) ? 0
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1826
                : workers.size();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1827
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1828
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1829
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1830
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1831
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1832
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1833
     * Returns the approximate number of threads that are actively
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1834
     * executing tasks.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1835
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1836
     * @return the number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1837
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1838
    public int getActiveCount() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1839
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1840
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1841
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1842
            int n = 0;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1843
            for (Worker w : workers)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1844
                if (w.isLocked())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1845
                    ++n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1846
            return n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1847
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1848
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1849
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1850
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1851
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1852
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1853
     * Returns the largest number of threads that have ever
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1854
     * simultaneously been in the pool.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1855
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1856
     * @return the number of threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1857
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1858
    public int getLargestPoolSize() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1859
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1860
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1861
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1862
            return largestPoolSize;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1863
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1864
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1865
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1866
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1867
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1868
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1869
     * Returns the approximate total number of tasks that have ever been
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1870
     * scheduled for execution. Because the states of tasks and
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1871
     * threads may change dynamically during computation, the returned
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1872
     * value is only an approximation.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1873
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1874
     * @return the number of tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1875
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1876
    public long getTaskCount() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1877
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1878
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1879
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1880
            long n = completedTaskCount;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1881
            for (Worker w : workers) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1882
                n += w.completedTasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1883
                if (w.isLocked())
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1884
                    ++n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1885
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1886
            return n + workQueue.size();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1887
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1888
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1889
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1890
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1891
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1892
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1893
     * Returns the approximate total number of tasks that have
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1894
     * completed execution. Because the states of tasks and threads
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1895
     * may change dynamically during computation, the returned value
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1896
     * is only an approximation, but one that does not ever decrease
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1897
     * across successive calls.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1898
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1899
     * @return the number of tasks
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1900
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1901
    public long getCompletedTaskCount() {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1902
        final ReentrantLock mainLock = this.mainLock;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1903
        mainLock.lock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1904
        try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1905
            long n = completedTaskCount;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1906
            for (Worker w : workers)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1907
                n += w.completedTasks;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1908
            return n;
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1909
        } finally {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1910
            mainLock.unlock();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1911
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1912
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1913
7976
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1914
    /**
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1915
     * Returns a string identifying this pool, as well as its state,
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1916
     * including indications of run state and estimated worker and
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1917
     * task counts.
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1918
     *
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1919
     * @return a string identifying this pool, as well as its state
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1920
     */
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1921
    public String toString() {
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1922
        long ncompleted;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1923
        int nworkers, nactive;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1924
        final ReentrantLock mainLock = this.mainLock;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1925
        mainLock.lock();
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1926
        try {
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1927
            ncompleted = completedTaskCount;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1928
            nactive = 0;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1929
            nworkers = workers.size();
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1930
            for (Worker w : workers) {
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1931
                ncompleted += w.completedTasks;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1932
                if (w.isLocked())
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1933
                    ++nactive;
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1934
            }
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1935
        } finally {
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1936
            mainLock.unlock();
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1937
        }
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1938
        int c = ctl.get();
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1939
        String runState =
47307
6864969a78ad 8186056: Miscellaneous changes imported from jsr166 CVS 2017-09
dl
parents: 47216
diff changeset
  1940
            isRunning(c) ? "Running" :
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1941
            runStateAtLeast(c, TERMINATED) ? "Terminated" :
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1942
            "Shutting down";
7976
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1943
        return super.toString() +
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1944
            "[" + runState +
7976
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1945
            ", pool size = " + nworkers +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1946
            ", active threads = " + nactive +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1947
            ", queued tasks = " + workQueue.size() +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1948
            ", completed tasks = " + ncompleted +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1949
            "]";
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1950
    }
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  1951
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1952
    /* Extension hooks */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1953
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1954
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1955
     * Method invoked prior to executing the given Runnable in the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1956
     * given thread.  This method is invoked by thread {@code t} that
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1957
     * will execute task {@code r}, and may be used to re-initialize
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1958
     * ThreadLocals, or to perform logging.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1959
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1960
     * <p>This implementation does nothing, but may be customized in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1961
     * subclasses. Note: To properly nest multiple overridings, subclasses
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1962
     * should generally invoke {@code super.beforeExecute} at the end of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1963
     * this method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1964
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1965
     * @param t the thread that will run task {@code r}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1966
     * @param r the task that will be executed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1967
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1968
    protected void beforeExecute(Thread t, Runnable r) { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1969
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1970
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1971
     * Method invoked upon completion of execution of the given Runnable.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1972
     * This method is invoked by the thread that executed the task. If
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1973
     * non-null, the Throwable is the uncaught {@code RuntimeException}
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1974
     * or {@code Error} that caused execution to terminate abruptly.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1975
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1976
     * <p>This implementation does nothing, but may be customized in
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1977
     * subclasses. Note: To properly nest multiple overridings, subclasses
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1978
     * should generally invoke {@code super.afterExecute} at the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1979
     * beginning of this method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1980
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1981
     * <p><b>Note:</b> When actions are enclosed in tasks (such as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1982
     * {@link FutureTask}) either explicitly or via methods such as
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1983
     * {@code submit}, these task objects catch and maintain
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1984
     * computational exceptions, and so they do not cause abrupt
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1985
     * termination, and the internal exceptions are <em>not</em>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1986
     * passed to this method. If you would like to trap both kinds of
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1987
     * failures in this method, you can further probe for such cases,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1988
     * as in this sample subclass that prints either the direct cause
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1989
     * or the underlying exception if a task has been aborted:
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1990
     *
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1991
     * <pre> {@code
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1992
     * class ExtendedExecutor extends ThreadPoolExecutor {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1993
     *   // ...
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1994
     *   protected void afterExecute(Runnable r, Throwable t) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1995
     *     super.afterExecute(r, t);
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1996
     *     if (t == null
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1997
     *         && r instanceof Future<?>
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  1998
     *         && ((Future<?>)r).isDone()) {
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  1999
     *       try {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2000
     *         Object result = ((Future<?>) r).get();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2001
     *       } catch (CancellationException ce) {
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  2002
     *         t = ce;
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2003
     *       } catch (ExecutionException ee) {
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  2004
     *         t = ee.getCause();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2005
     *       } catch (InterruptedException ie) {
32991
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  2006
     *         // ignore/reset
b27c76b82713 8134853: Bulk integration of java.util.concurrent classes
dl
parents: 25859
diff changeset
  2007
     *         Thread.currentThread().interrupt();
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2008
     *       }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2009
     *     }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2010
     *     if (t != null)
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2011
     *       System.out.println(t);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2012
     *   }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2013
     * }}</pre>
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2014
     *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2015
     * @param r the runnable that has completed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2016
     * @param t the exception that caused termination, or null if
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2017
     * execution completed normally
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2018
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2019
    protected void afterExecute(Runnable r, Throwable t) { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2020
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2021
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2022
     * Method invoked when the Executor has terminated.  Default
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2023
     * implementation does nothing. Note: To properly nest multiple
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2024
     * overridings, subclasses should generally invoke
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2025
     * {@code super.terminated} within this method.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2026
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2027
    protected void terminated() { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2028
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2029
    /* Predefined RejectedExecutionHandlers */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2030
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2031
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2032
     * A handler for rejected tasks that runs the rejected task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2033
     * directly in the calling thread of the {@code execute} method,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2034
     * unless the executor has been shut down, in which case the task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2035
     * is discarded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2036
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2037
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2038
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2039
         * Creates a {@code CallerRunsPolicy}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2040
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2041
        public CallerRunsPolicy() { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2042
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2043
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2044
         * Executes task r in the caller's thread, unless the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2045
         * has been shut down, in which case the task is discarded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2046
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2047
         * @param r the runnable task requested to be executed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2048
         * @param e the executor attempting to execute this task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2049
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2050
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2051
            if (!e.isShutdown()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2052
                r.run();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2053
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2054
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2055
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2056
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2057
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2058
     * A handler for rejected tasks that throws a
45936
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  2059
     * {@link RejectedExecutionException}.
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  2060
     *
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  2061
     * This is the default handler for {@link ThreadPoolExecutor} and
d564ef4bed8f 8177632: ScheduledThreadPoolExecutor delayed task shutdown policy affects non-scheduled tasks
dl
parents: 44534
diff changeset
  2062
     * {@link ScheduledThreadPoolExecutor}.
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2063
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2064
    public static class AbortPolicy implements RejectedExecutionHandler {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2065
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2066
         * Creates an {@code AbortPolicy}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2067
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2068
        public AbortPolicy() { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2069
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2070
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2071
         * Always throws RejectedExecutionException.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2072
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2073
         * @param r the runnable task requested to be executed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2074
         * @param e the executor attempting to execute this task
18790
d25399d849bc 8019370: Sync j.u.c Fork/Join from 166 to tl
psandoz
parents: 16079
diff changeset
  2075
         * @throws RejectedExecutionException always
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2076
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2077
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
7976
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  2078
            throw new RejectedExecutionException("Task " + r.toString() +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  2079
                                                 " rejected from " +
f273c0d04215 7005424: Resync java.util.concurrent classes with Dougs CVS - Jan 2011
dl
parents: 5506
diff changeset
  2080
                                                 e.toString());
2
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2081
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2082
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2083
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2084
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2085
     * A handler for rejected tasks that silently discards the
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2086
     * rejected task.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2087
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2088
    public static class DiscardPolicy implements RejectedExecutionHandler {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2089
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2090
         * Creates a {@code DiscardPolicy}.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2091
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2092
        public DiscardPolicy() { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2093
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2094
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2095
         * Does nothing, which has the effect of discarding task r.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2096
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2097
         * @param r the runnable task requested to be executed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2098
         * @param e the executor attempting to execute this task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2099
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2100
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2101
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2102
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2103
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2104
    /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2105
     * A handler for rejected tasks that discards the oldest unhandled
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2106
     * request and then retries {@code execute}, unless the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2107
     * is shut down, in which case the task is discarded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2108
     */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2109
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2110
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2111
         * Creates a {@code DiscardOldestPolicy} for the given executor.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2112
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2113
        public DiscardOldestPolicy() { }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2114
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2115
        /**
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2116
         * Obtains and ignores the next task that the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2117
         * would otherwise execute, if one is immediately available,
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2118
         * and then retries execution of task r, unless the executor
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2119
         * is shut down, in which case task r is instead discarded.
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2120
         *
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2121
         * @param r the runnable task requested to be executed
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2122
         * @param e the executor attempting to execute this task
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2123
         */
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2124
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2125
            if (!e.isShutdown()) {
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2126
                e.getQueue().poll();
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2127
                e.execute(r);
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2128
            }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2129
        }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2130
    }
90ce3da70b43 Initial load
duke
parents:
diff changeset
  2131
}