ShutdownNow Drains Queued Tasks
Call shutdownNow on a busy single-thread executor to interrupt the running task and drain the queue: it returns the runnables that never commenced.
Code
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class GracefulAbandon {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Future<String> running = pool.submit(() -> {
started.countDown();
try {
release.await(); // 阻塞点:shutdownNow 的中断会让它抛异常
} catch (InterruptedException e) {
return "interrupted";
}
return "finished";
});
Future<String> queuedA = pool.submit(() -> "queued-a");
Future<String> queuedB = pool.submit(() -> "queued-b");
started.await(); // 第一个 task 已在运行,另外两个仍 queued 在队列里
List<Runnable> neverStarted = pool.shutdownNow(); // 抽走 queued tasks
System.out.println("drained queued: " + neverStarted.size());
release.countDown();
System.out.println("running result: " + running.get());
// 被撤下的排队任务对应的 future 直接标记为已取消
System.out.println("queued futures done: " + queuedA.isDone() + " / " + queuedB.isDone());
}
}How it works
ShutdownNow Drains Queued Tasks comes down to the class GracefulAbandon.
Points of care
- Runs with what the toolchain already gives you — nothing extra.
Putting it to use
Output lines are prefixed (drained queued:, running result:, queued futures done:), making each step’s effect easy to spot.
Core lines
ExecutorService pool = Executors.newSingleThreadExecutor();
return "interrupted";
return "finished";
Interactive Tools for This Topic
FAQ
- What does ShutdownNow Drains Queued Tasks print when run?
- Running the file directly is enough — expect labeled output lines such as `drained queued:`, `running result:`, `queued futures done:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.