GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — SingleThreadEventExecutor: reject tasks that race never-started termi… · netty/netty@fae4cca

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • common/src
    • main/java/io/netty/util/concurrent
      • SingleThreadEventExecutor.java
    • test/java/io/netty/util/concurrent
      • SingleThreadEventExecutorTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java‎

Copy file name to clipboardExpand all lines: common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
+49-12Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,7 +1232,10 @@ private boolean ensureThreadStarted(int oldState) {
12321232

12331233
if (oldState == ST_NOT_STARTED || oldState == ST_SUSPENDED) {
12341234
try {
1235-
issueDoStartThread();
1235+
// Not gated by threadStartIssued. A worker that is still winding down may hold
1236+
// that flag; skipping here would leave shutdown waiting for a thread that never
1237+
// starts. processingLock serializes the two runnables.
1238+
doStartThread();
12361239
} catch (Throwable cause) {
12371240
STATE_UPDATER.set(this, ST_TERMINATED);
12381241
terminationFuture.tryFailure(cause);
@@ -1304,39 +1307,62 @@ private void onNeverStartedQuietPeriodTimer() {
13041307
* If this executor was never started and has no pending work, transition straight to
13051308
* {@link #ST_TERMINATED} without creating a thread.
13061309
*
1307-
* @return {@code true} if termination completed (or was already complete) without starting
1308-
* a thread; {@code false} if a thread still needs to be started to drain work / run shutdown.
1310+
* @return {@code true} if the caller must not start a thread: termination completed
1311+
* without a worker, or this method already issued one for work that was queued before
1312+
* {@link #ST_SHUTDOWN}. {@code false} if the caller should start a thread.
13091313
*/
13101314
private boolean tryTerminateIfNeverStarted() {
13111315
// Try to take the processing lock so we do not race with a just-started worker thread.
13121316
// If the lock is held, a thread is (or will be) running — fall back to the normal path.
13131317
if (!processingLock.tryLock()) {
13141318
return false;
13151319
}
1320+
boolean claimedStart = false;
1321+
boolean keepClaim = false;
13161322
try {
1317-
if (thread != null) {
1323+
if (thread != null || hasPendingWork()) {
13181324
return false;
13191325
}
1320-
// Re-check work under the lock. taskQueue / scheduled queue may have received a task
1321-
// after shutdown0 observed ST_NOT_STARTED (execute accepts tasks while SHUTTING_DOWN).
1322-
if (!taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty()) {
1326+
// issueDoStartThread() and this termination must exclude each other. A worker that
1327+
// already passed the gate is waiting on processingLock; do not terminate under it.
1328+
if (!threadStartIssued.compareAndSet(false, true)) {
13231329
return false;
13241330
}
1331+
claimedStart = true;
13251332

13261333
for (;;) {
13271334
int currentState = state;
13281335
if (currentState >= ST_TERMINATED) {
1336+
keepClaim = true;
13291337
return true;
13301338
}
13311339
if (currentState < ST_SHUTTING_DOWN) {
13321340
// Unexpected: state moved backwards from shutting down. Fall back.
13331341
return false;
13341342
}
1335-
// Work may have appeared after the empty check above.
1336-
if (!taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty()) {
1343+
if (hasPendingWork()) {
13371344
return false;
13381345
}
1346+
// SHUTTING_DOWN still accepts tasks. Publish SHUTDOWN before the last emptiness
1347+
// check so an execute() in that window is rejected instead of queued and then
1348+
// discarded by drainTasks(), which also used to let a worker run after cleanup().
1349+
if (currentState == ST_SHUTTING_DOWN) {
1350+
if (!STATE_UPDATER.compareAndSet(this, ST_SHUTTING_DOWN, ST_SHUTDOWN)) {
1351+
continue;
1352+
}
1353+
currentState = ST_SHUTDOWN;
1354+
}
1355+
if (hasPendingWork()) {
1356+
// Accepted before ST_SHUTDOWN. startThread() will not start a worker once the
1357+
// state has left SHUTTING_DOWN, so issue one here.
1358+
threadStartIssued.set(false);
1359+
claimedStart = false;
1360+
issueDoStartThread();
1361+
keepClaim = true;
1362+
return true;
1363+
}
13391364
if (STATE_UPDATER.compareAndSet(this, currentState, ST_TERMINATED)) {
1365+
keepClaim = true;
13401366
try {
13411367
// Subclass cleanup (e.g. SingleThreadIoEventLoop) may assert
13421368
// inEventLoop() and must still destroy constructor-created
@@ -1363,10 +1389,17 @@ private boolean tryTerminateIfNeverStarted() {
13631389
}
13641390
}
13651391
} finally {
1392+
if (claimedStart && !keepClaim) {
1393+
threadStartIssued.set(false);
1394+
}
13661395
processingLock.unlock();
13671396
}
13681397
}
13691398

1399+
private boolean hasPendingWork() {
1400+
return !taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty();
1401+
}
1402+
13701403
private void doStartThread() {
13711404
executor.execute(new Runnable() {
13721405
@Override
@@ -1442,10 +1475,12 @@ public void run() {
14421475
}
14431476

14441477
try {
1445-
if (shutdown) {
1478+
if (shutdown && state != ST_TERMINATED) {
14461479
// Run all remaining tasks and shutdown hooks. At this point the event loop
14471480
// is in ST_SHUTTING_DOWN state still accepting tasks which is needed for
14481481
// graceful shutdown with quietPeriod.
1482+
// A second worker can be inside doStartThread() after the first already
1483+
// published ST_TERMINATED; it must not complete the future again.
14491484
for (;;) {
14501485
if (confirmShutdown()) {
14511486
break;
@@ -1468,7 +1503,7 @@ public void run() {
14681503
}
14691504
} finally {
14701505
try {
1471-
if (shutdown) {
1506+
if (shutdown && state != ST_TERMINATED) {
14721507
try {
14731508
cleanup();
14741509
} finally {
@@ -1510,7 +1545,9 @@ public void run() {
15101545
int currentState = state;
15111546
if (currentState == ST_STARTED
15121547
|| (currentState >= ST_SHUTTING_DOWN && currentState < ST_TERMINATED)) {
1513-
issueDoStartThread();
1548+
// Direct start: issueDoStartThread() would no-op if this winding-down
1549+
// worker had not cleared the gate yet, or if a racer still holds it.
1550+
doStartThread();
15141551
}
15151552
}
15161553
}
Collapse file

‎common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java‎

Copy file name to clipboardExpand all lines: common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java
+98Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import org.junit.jupiter.api.function.Executable;
2222

2323
import java.util.Collections;
24+
import java.util.Queue;
2425
import java.util.Set;
2526
import java.util.concurrent.Callable;
2627
import java.util.concurrent.CountDownLatch;
@@ -1097,4 +1098,101 @@ protected void run() {
10971098
assertTrue(threadsCreated.get() >= 1);
10981099
assertTrue(executor.isTerminated());
10991100
}
1101+
1102+
/**
1103+
* execute() during never-started termination must run or be rejected.
1104+
* It must not be accepted and then dropped, and it must not start a worker after cleanup().
1105+
*/
1106+
@Test
1107+
@Timeout(value = 10, unit = TimeUnit.SECONDS)
1108+
public void testExecuteDuringNeverStartedTerminationIsNotDropped() throws Exception {
1109+
final AtomicInteger threadsCreated = new AtomicInteger();
1110+
final AtomicInteger cleanups = new AtomicInteger();
1111+
final AtomicBoolean runAfterCleanup = new AtomicBoolean();
1112+
final AtomicBoolean taskRan = new AtomicBoolean();
1113+
final AtomicBoolean rejected = new AtomicBoolean();
1114+
final AtomicInteger shutdownEmptyChecks = new AtomicInteger();
1115+
final CountDownLatch inWindow = new CountDownLatch(1);
1116+
final CountDownLatch release = new CountDownLatch(1);
1117+
ThreadFactory threadFactory = new ThreadFactory() {
1118+
private final AtomicInteger idx = new AtomicInteger();
1119+
@Override
1120+
public Thread newThread(@NotNull Runnable r) {
1121+
threadsCreated.incrementAndGet();
1122+
return new Thread(r, "never-started-race-" + idx.getAndIncrement());
1123+
}
1124+
};
1125+
1126+
final SingleThreadEventExecutor executor =
1127+
new SingleThreadEventExecutor(null, threadFactory, true) {
1128+
@Override
1129+
protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
1130+
return new LinkedBlockingQueue<Runnable>() {
1131+
@Override
1132+
public boolean isEmpty() {
1133+
if (isShutdown() && shutdownEmptyChecks.getAndIncrement() == 0) {
1134+
inWindow.countDown();
1135+
try {
1136+
if (!release.await(5, TimeUnit.SECONDS)) {
1137+
Thread.currentThread().interrupt();
1138+
}
1139+
} catch (InterruptedException e) {
1140+
Thread.currentThread().interrupt();
1141+
}
1142+
}
1143+
return super.isEmpty();
1144+
}
1145+
};
1146+
}
1147+
1148+
@Override
1149+
protected void run() {
1150+
if (cleanups.get() > 0) {
1151+
runAfterCleanup.set(true);
1152+
}
1153+
while (!confirmShutdown()) {
1154+
Runnable task = takeTask();
1155+
if (task != null) {
1156+
task.run();
1157+
}
1158+
}
1159+
}
1160+
1161+
@Override
1162+
protected void cleanup() {
1163+
cleanups.incrementAndGet();
1164+
super.cleanup();
1165+
}
1166+
};
1167+
1168+
Thread shutdownThread = new Thread(new Runnable() {
1169+
@Override
1170+
public void run() {
1171+
executor.shutdownGracefully(0, 0, TimeUnit.SECONDS).syncUninterruptibly();
1172+
}
1173+
}, "never-started-shutdown");
1174+
shutdownThread.start();
1175+
assertTrue(inWindow.await(5, TimeUnit.SECONDS),
1176+
"termination must publish SHUTDOWN before the last empty check");
1177+
try {
1178+
executor.execute(new Runnable() {
1179+
@Override
1180+
public void run() {
1181+
taskRan.set(true);
1182+
}
1183+
});
1184+
} catch (RejectedExecutionException expected) {
1185+
rejected.set(true);
1186+
}
1187+
release.countDown();
1188+
shutdownThread.join(5_000);
1189+
assertFalse(shutdownThread.isAlive());
1190+
assertTrue(executor.terminationFuture().await(5, TimeUnit.SECONDS));
1191+
assertTrue(executor.isTerminated());
1192+
assertTrue(taskRan.get() || rejected.get(), "task must run or be rejected");
1193+
assertFalse(taskRan.get() && rejected.get());
1194+
assertFalse(runAfterCleanup.get(), "worker must not enter run() after cleanup()");
1195+
assertEquals(1, cleanups.get());
1196+
assertEquals(0, threadsCreated.get(), "rejected execute during termination must not start a worker");
1197+
}
11001198
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.