|
Expand Up
|
@@ -40,6 +40,7 @@ |
|
|
import java.util.concurrent.ThreadFactory; |
|
|
import java.util.concurrent.TimeUnit; |
|
|
import java.util.concurrent.TimeoutException; |
|
|
import java.util.concurrent.atomic.AtomicBoolean; |
|
|
import java.util.concurrent.atomic.AtomicInteger; |
|
|
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; |
|
|
import java.util.concurrent.atomic.AtomicLong; |
|
Expand Down
Expand Up
|
@@ -97,6 +98,12 @@ |
|
|
private final Lock processingLock = new ReentrantLock(); |
|
|
private final CountDownLatch threadLock = new CountDownLatch(1); |
|
|
private final Set<Runnable> shutdownHooks = new LinkedHashSet<Runnable>(); |
|
|
/** |
|
|
* Ensures at most one worker start is issued for this executor (including the |
|
|
* never-started → SHUTTING_DOWN path that must start a thread only if a task arrives |
|
|
* during the quiet period). |
|
|
*/ |
|
|
private final AtomicBoolean threadStartIssued = new AtomicBoolean(); |
|
|
private final boolean addTaskWakesUp; |
|
|
private final int maxPendingTasks; |
|
|
private final RejectedExecutionHandler rejectedExecutionHandler; |
|
Expand Down
Expand Up
|
@@ -128,6 +135,13 @@ |
|
|
|
|
|
private final Promise<?> terminationFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE); |
|
|
|
|
|
private final Runnable neverStartedQuietPeriodTask = new Runnable() { |
|
|
@Override |
|
|
public void run() { |
|
|
onNeverStartedQuietPeriodTimer(); |
|
|
} |
|
|
}; |
|
|
|
|
|
/** |
|
|
* Create a new instance |
|
|
* |
|
Expand Down
Expand Up
|
@@ -363,7 +377,7 @@ |
|
|
if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { |
|
|
return false; |
|
|
} |
|
|
long nanoTime = getCurrentTimeNanos(); |
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / verify-pr
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / windows-x86_64-java11-boringssl
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (cpp)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (java)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-aarch64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 380
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-x86_64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
|
|
|
Runnable scheduledTask = pollScheduledTask(nanoTime); |
|
|
if (scheduledTask == null) { |
|
|
return false; |
|
Expand Down
Expand Up
|
@@ -440,7 +454,7 @@ |
|
|
} while (!fetchedAll); // keep on processing until we fetched all scheduled tasks. |
|
|
|
|
|
if (ranAtLeastOne) { |
|
|
lastExecutionTime = getCurrentTimeNanos(); |
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / verify-pr
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / windows-x86_64-java11-boringssl
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (cpp)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (java)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-aarch64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 457
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-x86_64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
|
|
|
} |
|
|
afterRunningAllTasks(); |
|
|
return ranAtLeastOne; |
|
Expand All
|
@@ -465,7 +479,7 @@ |
|
|
} while (ranAtLeastOneTask && ++drainAttempt < maxDrainAttempts); |
|
|
|
|
|
if (drainAttempt > 0) { |
|
|
lastExecutionTime = getCurrentTimeNanos(); |
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / verify-pr
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / windows-x86_64-java11-boringssl
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (cpp)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / Analyze (java)
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-aarch64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Check warning
on line 482
in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
View workflow job for this annotation
GitHub Actions / macos-x86_64-java11-boringssl build
[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
|
|
|
} |
|
|
afterRunningAllTasks(); |
|
|
|
|
Expand Down
Expand Up
|
@@ -1158,27 +1172,69 @@ |
|
|
resetBusyCycles(); |
|
|
boolean success = false; |
|
|
try { |
|
|
doStartThread(); |
|
|
issueDoStartThread(); |
|
|
success = true; |
|
|
// execute() may have moved ST_SUSPENDED -> ST_STARTED while this thread is still |
|
|
// winding down; wake it so it re-engages instead of exiting with no replacement. |
|
|
if (currentState == ST_SUSPENDED && thread != null) { |
|
|
wakeup(false); |
|
|
} |
|
|
} finally { |
|
|
if (!success) { |
|
|
STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_NOT_STARTED); |
|
|
threadStartIssued.set(false); |
|
|
} |
|
|
} |
|
|
break; |
|
|
} |
|
|
// The state changed after we read it. If trySuspend() moved it from ST_NOT_STARTED to ST_SUSPENDED no |
|
|
// thread was started, so we need to try again. Otherwise the task that was just added might never run. |
|
|
// This may deliberately un-suspend an executor that trySuspend() has just suspended, which is the same |
|
|
// thing execute() does for an executor that is already suspended. We only loop again if another thread |
|
|
// changed the state in between, so this can't spin. |
|
|
// The state changed after we read it. If trySuspend() moved it from ST_NOT_STARTED to |
|
|
// ST_SUSPENDED no thread was started, so we need to try again. Otherwise the task that |
|
|
// was just added might never run. This may deliberately un-suspend an executor that |
|
|
// trySuspend() has just suspended, which is the same thing execute() does for an |
|
|
// executor that is already suspended. We only loop again if another thread changed the |
|
|
// state in between, so this can't spin. |
|
|
currentState = state; |
|
|
} |
|
|
if (currentState == ST_SHUTTING_DOWN && thread == null) { |
|
|
// Never-started executor already in graceful shutdown: a task arrived during the |
|
|
// quiet period. Start a worker without changing state away from SHUTTING_DOWN so |
|
|
// confirmShutdown still honors quietPeriod/timeout (#17135 + quiet-period accept). |
|
|
// A successful start above breaks with currentState still NOT_STARTED or SUSPENDED, |
|
|
// so this branch does not also run. |
|
|
try { |
|
|
issueDoStartThread(); |
|
|
} catch (Throwable cause) { |
|
|
STATE_UPDATER.set(this, ST_TERMINATED); |
|
|
terminationFuture.tryFailure(cause); |
|
|
if (!(cause instanceof Exception)) { |
|
|
PlatformDependent.throwException(cause); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
private boolean ensureThreadStarted(int oldState) { |
|
|
// Never-started shutdown (#17135): |
|
|
// - quietPeriod == 0: terminate immediately without creating a worker. |
|
|
// - quietPeriod > 0: stay SHUTTING_DOWN without a worker; schedule a timer to |
|
|
// terminate when the quiet period elapses with no tasks. execute() during that |
|
|
// window starts a worker via startThread() (ST_SHUTTING_DOWN + thread == null). |
|
|
if (oldState == ST_NOT_STARTED) { |
|
|
if (gracefulShutdownQuietPeriod == 0) { |
|
|
if (tryTerminateIfNeverStarted()) { |
|
|
return true; |
|
|
} |
|
|
} else { |
|
|
scheduleNeverStartedQuietPeriodExpire(); |
|
|
return true; |
|
|
} |
|
|
} |
|
|
|
|
|
if (oldState == ST_NOT_STARTED || oldState == ST_SUSPENDED) { |
|
|
try { |
|
|
// Not gated by threadStartIssued. A worker that is still winding down may hold |
|
|
// that flag; skipping here would leave shutdown waiting for a thread that never |
|
|
// starts. processingLock serializes the two runnables. |
|
|
doStartThread(); |
|
|
} catch (Throwable cause) { |
|
|
STATE_UPDATER.set(this, ST_TERMINATED); |
|
Expand All
|
@@ -1194,6 +1250,156 @@ |
|
|
return false; |
|
|
} |
|
|
|
|
|
/** |
|
|
* Issue at most one {@link #doStartThread()} for this executor. |
|
|
*/ |
|
|
private void issueDoStartThread() { |
|
|
if (!threadStartIssued.compareAndSet(false, true)) { |
|
|
return; |
|
|
} |
|
|
try { |
|
|
doStartThread(); |
|
|
} catch (Throwable t) { |
|
|
threadStartIssued.set(false); |
|
|
PlatformDependent.throwException(t); |
|
|
} |
|
|
} |
|
|
|
|
|
/** |
|
|
* Schedule termination (or late worker start if work appears) for a never-started |
|
|
* executor that entered {@link #ST_SHUTTING_DOWN} with a non-zero quiet period. |
|
|
*/ |
|
|
private void scheduleNeverStartedQuietPeriodExpire() { |
|
|
if (gracefulShutdownStartTime == 0) { |
|
|
gracefulShutdownStartTime = getCurrentTimeNanos(); |
|
|
} |
|
|
// Treat "no tasks yet" as last activity at shutdown start so quiet-period math matches |
|
|
// confirmShutdown when a worker is started later. |
|
|
lastExecutionTime = gracefulShutdownStartTime; |
|
|
|
|
|
final long quietNanos = gracefulShutdownQuietPeriod; |
|
|
final long timeoutNanos = gracefulShutdownTimeout; |
|
|
// Fire at quiet-period end (and again at timeout if longer) so we still terminate if |
|
|
// the first timer races with a late execute that then drains before the second fire. |
|
|
GlobalEventExecutor.INSTANCE.schedule(neverStartedQuietPeriodTask, quietNanos, TimeUnit.NANOSECONDS); |
|
|
if (timeoutNanos > quietNanos) { |
|
|
GlobalEventExecutor.INSTANCE.schedule(neverStartedQuietPeriodTask, timeoutNanos, TimeUnit.NANOSECONDS); |
|
|
} |
|
|
} |
|
|
|
|
|
private void onNeverStartedQuietPeriodTimer() { |
|
|
if (thread != null || isTerminated() || !isShuttingDown()) { |
|
|
return; |
|
|
} |
|
|
// Work pending → start worker under SHUTTING_DOWN so confirmShutdown drains it. |
|
|
if (!taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty()) { |
|
|
startThread(); |
|
|
return; |
|
|
} |
|
|
if (tryTerminateIfNeverStarted()) { |
|
|
return; |
|
|
} |
|
|
// Race: work appeared after empty check. |
|
|
startThread(); |
|
|
} |
|
|
|
|
|
/** |
|
|
* If this executor was never started and has no pending work, transition straight to |
|
|
* {@link #ST_TERMINATED} without creating a thread. |
|
|
* |
|
|
* @return {@code true} if the caller must not start a thread: termination completed |
|
|
* without a worker, or this method already issued one for work that was queued before |
|
|
* {@link #ST_SHUTDOWN}. {@code false} if the caller should start a thread. |
|
|
*/ |
|
|
private boolean tryTerminateIfNeverStarted() { |
|
|
// Try to take the processing lock so we do not race with a just-started worker thread. |
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The lock only protects against a worker that already holds it. A worker issued while this method runs waits on
processingLock.lock() (:1360), and it runs right after we release the lock, with the state already
ST_TERMINATED.
Claude Code on behalf of allthingssecurity
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
|
// If the lock is held, a thread is (or will be) running — fall back to the normal path. |
|
|
if (!processingLock.tryLock()) { |
|
|
return false; |
|
|
} |
|
|
boolean claimedStart = false; |
|
|
boolean keepClaim = false; |
|
|
try { |
|
|
if (thread != null || hasPendingWork()) { |
|
|
return false; |
|
|
} |
|
|
// issueDoStartThread() and this termination must exclude each other. A worker that |
|
|
// already passed the gate is waiting on processingLock; do not terminate under it. |
|
|
if (!threadStartIssued.compareAndSet(false, true)) { |
|
|
return false; |
|
|
} |
|
|
claimedStart = true; |
|
|
|
|
|
for (;;) { |
|
|
int currentState = state; |
|
|
if (currentState >= ST_TERMINATED) { |
|
|
keepClaim = true; |
|
|
return true; |
|
|
} |
|
|
if (currentState < ST_SHUTTING_DOWN) { |
|
|
// Unexpected: state moved backwards from shutting down. Fall back. |
|
|
return false; |
|
|
} |
|
|
if (hasPendingWork()) { |
|
|
return false; |
|
|
} |
|
|
// SHUTTING_DOWN still accepts tasks. Publish SHUTDOWN before the last emptiness |
|
|
// check so an execute() in that window is rejected instead of queued and then |
|
|
// discarded by drainTasks(), which also used to let a worker run after cleanup(). |
|
|
if (currentState == ST_SHUTTING_DOWN) { |
|
|
if (!STATE_UPDATER.compareAndSet(this, ST_SHUTTING_DOWN, ST_SHUTDOWN)) { |
|
|
continue; |
|
|
} |
|
|
currentState = ST_SHUTDOWN; |
|
|
} |
|
|
if (hasPendingWork()) { |
|
|
// Accepted before ST_SHUTDOWN. startThread() will not start a worker once the |
|
|
// state has left SHUTTING_DOWN, so issue one here. |
|
|
threadStartIssued.set(false); |
|
|
claimedStart = false; |
|
|
issueDoStartThread(); |
|
|
keepClaim = true; |
|
|
return true; |
|
|
} |
|
|
if (STATE_UPDATER.compareAndSet(this, currentState, ST_TERMINATED)) { |
Comment thread
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
An execute() that runs between the check above and this CAS gets lost. addTask succeeds. startThread() takes
the ST_SHUTTING_DOWN && thread == null branch and issues a worker, which blocks on processingLock.
isShutdown() is still false, so the task is not rejected. After the CAS, drainTasks() below discards it, and the
blocked worker then enters run() on the terminated executor. Deterministic reproducer and numbers are in the
review body.
Claude Code on behalf of allthingssecurity
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
|
keepClaim = true; |
|
|
try { |
|
|
// Subclass cleanup (e.g. SingleThreadIoEventLoop) may assert |
|
|
// inEventLoop() and must still destroy constructor-created |
|
|
// resources (IoHandler / native FDs). Bind the current thread |
|
|
// as the event-loop thread only for cleanup; run() never ran |
|
|
// so there is no concurrent event-loop activity. |
|
|
assert thread == null; |
|
|
thread = Thread.currentThread(); |
|
|
try { |
|
|
cleanup(); |
|
|
} finally { |
|
|
thread = null; |
|
|
} |
|
|
} finally { |
|
|
threadLock.countDown(); |
|
|
int numUserTasks = drainTasks(); |
|
|
if (numUserTasks > 0 && logger.isWarnEnabled()) { |
|
|
logger.warn("An event executor terminated with " + |
|
|
"non-empty task queue (" + numUserTasks + ')'); |
|
|
} |
|
|
terminationFuture.setSuccess(null); |
|
|
} |
|
|
return true; |
|
|
} |
|
|
} |
|
|
} finally { |
|
|
if (claimedStart && !keepClaim) { |
|
|
threadStartIssued.set(false); |
|
|
} |
|
|
processingLock.unlock(); |
|
|
} |
|
|
} |
|
|
|
|
|
private boolean hasPendingWork() { |
|
|
return !taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty(); |
|
|
} |
|
|
|
|
|
private void doStartThread() { |
|
|
executor.execute(new Runnable() { |
|
|
@Override |
|
Expand Down
Expand Up
|
@@ -1226,10 +1432,11 @@ |
|
|
continue; |
|
|
} |
|
|
|
|
|
if (!canSuspend(ST_SUSPENDED) && STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this, |
|
|
ST_SUSPENDED, ST_STARTED)) { |
|
|
// Seems like there was something added to the task queue again in the meantime but we |
|
|
// were able to re-engage this thread as the event loop thread. |
|
|
if (!canSuspend(ST_SUSPENDED)) { |
|
|
// Work arrived while suspending. execute() may already have moved us to |
|
|
// ST_STARTED; re-engage this thread in either case. |
|
|
STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this, |
|
|
ST_SUSPENDED, ST_STARTED); |
|
|
continue; |
|
|
} |
|
|
suspend = true; |
|
Expand Down
Expand Up
|
@@ -1268,10 +1475,12 @@ |
|
|
} |
|
|
|
|
|
try { |
|
|
if (shutdown) { |
|
|
if (shutdown && state != ST_TERMINATED) { |
|
|
// Run all remaining tasks and shutdown hooks. At this point the event loop |
|
|
// is in ST_SHUTTING_DOWN state still accepting tasks which is needed for |
|
|
// graceful shutdown with quietPeriod. |
|
|
// A second worker can be inside doStartThread() after the first already |
|
|
// published ST_TERMINATED; it must not complete the future again. |
|
|
for (;;) { |
|
|
if (confirmShutdown()) { |
|
|
break; |
|
Expand All
|
@@ -1294,7 +1503,7 @@ |
|
|
} |
|
|
} finally { |
|
|
try { |
|
|
if (shutdown) { |
|
|
if (shutdown && state != ST_TERMINATED) { |
|
|
try { |
|
|
cleanup(); |
|
|
} finally { |
|
Expand Down
Expand Up
|
@@ -1326,8 +1535,20 @@ |
|
|
} |
|
|
} finally { |
|
|
thread = null; |
|
|
// Allow a later startThread()/issueDoStartThread() after suspension or |
|
|
// termination of this worker (suspension reuses the same executor). |
|
|
threadStartIssued.set(false); |
|
|
// Let the next thread take over if needed. |
|
|
processingLock.unlock(); |
|
|
// execute() or shutdown may have moved us to ST_STARTED / SHUTTING_DOWN |
|
|
// while this thread still held threadStartIssued (e.g. during removeAll). |
|
|
int currentState = state; |
|
|
if (currentState == ST_STARTED |
|
|
|| (currentState >= ST_SHUTTING_DOWN && currentState < ST_TERMINATED)) { |
|
|
// Direct start: issueDoStartThread() would no-op if this winding-down |
|
|
// worker had not cleared the gate yet, or if a racer still holds it. |
|
|
doStartThread(); |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
Expand Down
|
|