Stop worker threads cleanly
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Java has no safe way to force a thread to stop: the old Thread.stop() is deprecated because it can leave data half changed. A worker stops cleanly only when it is asked to and ends its own loop, and the way you ask decides whether queued work is finished or lost.
A volatile running flag versus interrupt
A running flag is a volatile boolean that the worker checks at the top of its loop; another thread sets it to false to ask the worker to stop. It works only if the worker comes back to the check often.
Example 1 · A running flag cannot stop a worker stuck in take()
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class FlagVersusInterruptDemo { static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException { BlockingQueue<String> orders = new ArrayBlockingQueue<>(5);
Thread worker = new Thread(() -> { try { while (running) { String order = orders.take(); // blocks: the queue is empty System.out.println("Packed " + order); } System.out.println("Worker: saw running = false"); } catch (InterruptedException e) { System.out.println("Worker: interrupted inside take(), stopping"); } }, "worker"); worker.start();
while (worker.getState() != Thread.State.WAITING) { // demo only: let it block in take() Thread.sleep(5); }
running = false; worker.join(300); System.out.println("After running = false: worker still alive? " + worker.isAlive());
worker.interrupt(); // wake it up worker.join(); System.out.println("After interrupt(): worker still alive? " + worker.isAlive()); }}After running = false: worker still alive? true Worker: interrupted inside take(), stopping After interrupt(): worker still alive? false
What this code does
- The flag is
volatile, so the worker would seefalseat once, but it never gets back to thewhile (running)check: it is asleep insidetake()waiting for an order that never comes. interrupt()makes the blockedtake()throwInterruptedException. The worker catches it and leaves its loop. Blocking calls such astake,put,sleep,waitandjoinall respond to an interrupt this way.
Example 2 · Interrupt stops at once and leaves work behind
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class InterruptLeavesWorkDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> orders = new ArrayBlockingQueue<>(10); for (int i = 1; i <= 5; i++) { orders.put("ORD-" + i); } int[] packed = {0};
Thread worker = new Thread(() -> { try { while (!Thread.currentThread().isInterrupted()) { String order = orders.take(); Thread.sleep(100); // packing takes 100 ms packed[0]++; } } catch (InterruptedException e) { // stop: we were asked to } }, "worker"); worker.start();
Thread.sleep(250); worker.interrupt(); worker.join(); System.out.println("Packed: " + packed[0]); System.out.println("Taken but not finished: " + (5 - packed[0] - orders.size())); System.out.println("Never started, still in the queue: " + orders.size()); }}Packed: 2 Taken but not finished: 1 Never started, still in the queue: 2
What this code does
- The interrupt arrives while the worker is packing the third order.
sleepthrows, so that order is half done, and two more orders are still waiting in the queue. The exact numbers depend on timing and can change from run to run. - Interrupt is the right tool to stop now: a blocked worker always wakes. But it does not finish anything, so on its own it is wrong when every queued order must still be handled.
Interrupting a thread with worker.interrupt() sets its interrupt flag and wakes it from blocking calls such as take, put, sleep, wait and join, which throw InterruptedException. It stops a worker quickly, but anything still in the queue, and the job in progress, are left behind. A worker blocked in take() on an empty queue never comes back.
- Flag: simple, but slow or stuck if the worker blocks.
- Interrupt: always wakes a blocked worker, but stops in the middle of the work.
- If you catch
InterruptedExceptiondeep inside a helper, callThread.currentThread().interrupt()to restore the flag so the loop can see it.
The poison pill message
A poison pill is a special message that the producer puts into the queue to mean "no more work". The consumer stops when it takes the pill. The queue is first-in, first-out, so every real item put before the pill is handled first.
Example 3 · Poison pill: stop after everything before it is done
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
record Order(String id) {}
public class PoisonPillDemo { static final Order POISON = new Order("POISON"); // one special object
public static void main(String[] args) throws InterruptedException { BlockingQueue<Order> orders = new ArrayBlockingQueue<>(3);
Thread worker = new Thread(() -> { int packed = 0; try { while (true) { Order o = orders.take(); if (o == POISON) { // same object, not just equal break; } System.out.println("Packed " + o.id()); packed++; } } catch (InterruptedException e) { return; } System.out.println("Worker: poison pill received after " + packed + " orders"); }, "worker"); worker.start();
for (int i = 1; i <= 5; i++) { orders.put(new Order("ORD-" + i)); } orders.put(POISON); // "no more work" worker.join(); System.out.println("Main: worker finished, queue empty? " + orders.isEmpty()); }}Packed ORD-1 Packed ORD-2 Packed ORD-3 Packed ORD-4 Packed ORD-5 Worker: poison pill received after 5 orders Main: worker finished, queue empty? true
What this code does
- The queue is first-in, first-out, so the pill comes out only after every order put before it. The worker finishes all 5 orders and then stops by itself.
POISONis one fixed object compared with==, so no real order can be mistaken for it, even one with the idPOISON. A record'sequalswould compare the id, which is why==is used here.
Example 4 · Three workers need three pills
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class ManyWorkersPillDemo { static final String POISON = new String("POISON"); // a unique object, compared with ==
public static void main(String[] args) throws InterruptedException { BlockingQueue<String> orders = new ArrayBlockingQueue<>(4); int workerCount = 3; List<List<String>> done = new ArrayList<>(); Thread[] workers = new Thread[workerCount];
for (int w = 0; w < workerCount; w++) { List<String> mine = new ArrayList<>(); done.add(mine); workers[w] = new Thread(() -> { try { String o; while ((o = orders.take()) != POISON) { mine.add(o); } } catch (InterruptedException e) { return; } }, "worker-" + (w + 1)); workers[w].start(); }
for (int i = 1; i <= 9; i++) { orders.put("ORD-" + i); } for (int w = 0; w < workerCount; w++) { orders.put(POISON); // one pill per worker } for (Thread t : workers) { t.join(); }
List<String> all = new ArrayList<>(); for (List<String> mine : done) { all.addAll(mine); } Collections.sort(all); System.out.println("Packed " + all.size() + ": " + all); System.out.println("Workers still running: " + (workers[0].isAlive() || workers[1].isAlive() || workers[2].isAlive())); }}Packed 9: [ORD-1, ORD-2, ORD-3, ORD-4, ORD-5, ORD-6, ORD-7, ORD-8, ORD-9] Workers still running: false
What this code does
- A worker that takes a pill stops and never takes another item. So each worker needs its own pill: with only one pill, one worker stops and the other two block in
take()forever. - All 9 orders sit in the queue ahead of the pills, so every order is packed before any worker stops. Which worker packs which order changes from run to run; the sorted list does not.
new String("POISON")makes an object that no other string shares, so==matches only the pill. This idea of a unique sentinel object works for any element type.
Use one unique object, such as static final Order POISON = new Order("POISON"), and compare with ==. With several consumers, put one pill per consumer: each consumer swallows exactly one pill and stops.
Draining remaining work before exit
Draining means handling, or saving, every item still in the queue before the worker exits, so nothing is lost silently. A poison pill drains by design.
Example 5 · Draining the queue before exit
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;
public class DrainBeforeExitDemo { static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException { // 1. Flag + timed poll: keep going until stopped AND the queue is empty. BlockingQueue<String> sms = new ArrayBlockingQueue<>(10); int[] sent = {0}; Thread sender = new Thread(() -> { try { while (running || !sms.isEmpty()) { String msg = sms.poll(50, TimeUnit.MILLISECONDS); if (msg != null) { sent[0]++; } } } catch (InterruptedException e) { return; } }, "sms-sender"); sender.start(); for (int i = 1; i <= 6; i++) { sms.put("OTP-" + i); } running = false; sender.join(); System.out.println("Flag + poll: sent " + sent[0] + " of 6");
// 2. Interrupt now, then save whatever is left for a retry. BlockingQueue<String> bills = new ArrayBlockingQueue<>(10); for (int i = 1; i <= 6; i++) { bills.put("BILL-" + i); } int[] printed = {0}; Thread printer = new Thread(() -> { try { while (true) { bills.take(); Thread.sleep(40); printed[0]++; } } catch (InterruptedException e) { return; } }, "printer"); printer.start(); Thread.sleep(100); printer.interrupt(); printer.join(); List<String> retry = new ArrayList<>(); bills.drainTo(retry); int lost = 6 - printed[0] - retry.size(); System.out.println("Interrupt + drainTo: printed + saved for retry + half-done = " + printed[0] + " + " + retry.size() + " + " + lost + " = 6"); }}Flag + poll: sent 6 of 6 Interrupt + drainTo: printed + saved for retry + half-done = 2 + 3 + 1 = 6
What this code does
- Part 1 drains: the loop runs
while (running || !queue.isEmpty()), and the timedpolllets it notice the flag even when the queue is empty. All 6 OTP messages are sent before the thread exits. - Part 2 stops at once with an interrupt, then
drainTomoves every item still in the queue into a retry list, so nothing is silently dropped. Only the bill being printed at the moment of the interrupt is half done. How the 6 split up changes from run to run.
With a running flag, make the worker loop while (running || !queue.isEmpty()) and use a timed poll so the worker can notice the flag when the queue is empty.
If you must stop at once with an interrupt, move the leftovers out with queue.drainTo(list) and save them for a retry or report them. Only the item being worked on at that moment can be half done.
Shutting down producers before consumers
Stop the threads in the direction the work flows. A pill must be the last item in the queue, so it can go in only after every producer has finished.
- Stop the producers, or let them finish, and
join()every one of them. - Put one poison pill per consumer into the queue.
join()the consumers; they finish the queued work and then take their pill.- In a pipeline with several stages, repeat this stage by stage: a stage that takes a pill passes one on to the next queue.
Example 6 · Stop producers first, then consumers
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class ShutdownOrderDemo { static final String POISON = new String("POISON");
static int[] run(boolean producersFirst) throws InterruptedException { BlockingQueue<String> orders = new ArrayBlockingQueue<>(20); int[] packed = {0};
Thread warehouse = new Thread(() -> { try { for (int i = 1; i <= 6; i++) { Thread.sleep(30); orders.put("ORD-" + i); } } catch (InterruptedException e) { return; } }, "warehouse"); Thread packer = new Thread(() -> { try { while (orders.take() != POISON) { packed[0]++; } } catch (InterruptedException e) { return; } }, "packer"); warehouse.start(); packer.start();
if (producersFirst) { warehouse.join(); // 1. no more orders can arrive orders.put(POISON); // 2. then the pill } else { orders.put(POISON); // wrong: the warehouse is still packing warehouse.join(); } packer.join(); return new int[] {packed[0], orders.size()}; }
public static void main(String[] args) throws InterruptedException { int[] wrong = run(false); System.out.println("Pill too early: packed " + wrong[0] + ", left in queue " + wrong[1]); int[] right = run(true); System.out.println("Producers first: packed " + right[0] + ", left in queue " + right[1]); }}Pill too early: packed 0, left in queue 6 Producers first: packed 6, left in queue 0
What this code does
- In the wrong order, the pill goes in while the warehouse is still packing, so it sits ahead of orders that come later. The packer stops at the pill and those orders are never packed. How many are lost depends on timing; here the pill beat all six.
- The safe order is: wait for every producer to finish (
join), then put one pill per consumer, then wait for the consumers. A pill must always be the last thing in the queue.
Next step
Check your understanding
12 quick questions