@@ -206,6 +206,54 @@ void testNotSuspendedUntilScheduledTaskIsCancelled() throws Exception { |
206 | 206 | } |
207 | 207 | } |
208 | 208 |
|
| 209 | + @Test |
| 210 | + @Timeout(value = 30, unit = TimeUnit.SECONDS) |
| 211 | + void testSuspendDoesNotRaceWithCancelledScheduledTask() throws Exception { |
| 212 | + // Regression test: cancelling a scheduled task right as the executor is about to suspend used to |
| 213 | + // be able to race with the suspend confirmation in doStartThread(). The cancelled task schedules |
| 214 | + // its own removal via scheduleRemoveScheduled(), which can land in the task queue in the tiny |
| 215 | + // window between run() deciding it can suspend and doStartThread() re-checking canSuspend(). |
| 216 | + // That caused the executor to treat the situation as if run() returned without confirming |
| 217 | + // shutdown, spuriously shutting itself down instead of suspending (or continuing to run). |
| 218 | + // The race is timing dependent, so we repeat the scenario many times to make a regression likely |
| 219 | + // to be caught. |
| 220 | + for (int i = 0; i < 2000; i++) { |
| 221 | + TestThreadFactory threadFactory = new TestThreadFactory(); |
| 222 | + final SingleThreadEventExecutor executor = new SuspendingSingleThreadEventExecutor(threadFactory); |
| 223 | + |
| 224 | + Future<?> future = executor.schedule(() -> { }, 1, TimeUnit.DAYS); |
| 225 | + TestThread currentThread = threadFactory.threads.take(); |
| 226 | + currentThread.awaitStarted(); |
| 227 | + currentThread.awaitRunnableExecution(); |
| 228 | + assertTrue(executor.trySuspend(), "iteration " + i); |
| 229 | + |
| 230 | + assertTrue(future.cancel(false), "iteration " + i); |
| 231 | + future.await(); |
| 232 | + |
| 233 | + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); |
| 234 | + while (!executor.trySuspend()) { |
| 235 | + if (System.nanoTime() > deadline) { |
| 236 | + fail("executor got stuck instead of suspending at iteration " + i |
| 237 | + + " (isShutdown=" + executor.isShutdown() + ')'); |
| 238 | + } |
| 239 | + Thread.sleep(1); |
| 240 | + } |
| 241 | + |
| 242 | + currentThread.join(TimeUnit.SECONDS.toMillis(2)); |
| 243 | + assertFalse(currentThread.isAlive(), "worker thread did not terminate at iteration " + i); |
| 244 | + |
| 245 | + assertTrue(executor.trySuspend(), "iteration " + i + " (isShutdown=" + executor.isShutdown() + ')'); |
| 246 | + assertTrue(executor.isSuspended(), "iteration " + i); |
| 247 | + |
| 248 | + executor.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly(); |
| 249 | + |
| 250 | + TestThread t; |
| 251 | + while ((t = threadFactory.threads.poll()) != null) { |
| 252 | + t.join(); |
| 253 | + } |
| 254 | + } |
| 255 | + } |
| 256 | + |
209 | 257 | @Test |
210 | 258 | void testNotSuspendedUntilScheduledTaskDidRun() throws Exception { |
211 | 259 | TestThreadFactory threadFactory = new TestThreadFactory(); |
|