SteelReed

Search

Search posts, questions…

3. Advanced Java

Threads in Java: creating threads, the lifecycle and interruption

What a thread is and how it differs from a process, concurrency vs parallelism, Thread/Runnable/Callable, start vs run, the six states you see in a thread dump, stopping a thread with interruption, and how to review AI-written multithreaded code.

17 Nov 20267 min readJunior

–

1. The problem

A rolling deploy gives a pod 30 seconds to stop. A worker catches InterruptedException, logs it and keeps going, so shutdownNow() can't stop it. After 30 seconds Kubernetes kills the process: 40 half-done jobs run again, and some emails go out twice.

2. Key idea

A process is a kitchen; threads are cooks sharing the pantry (heap), each with their own cutting board (stack). Nobody snatches the knife from a cook's hand: there's only a "take a break" call, and each cook picks when to stop. Snatching it mid-cut leaves shared data half-done; that's why Thread.stop() was removed.

State Meaning
NEW object created, not start()ed
RUNNABLE running or ready; also while blocked on a socket
BLOCKED waiting to enter a held synchronized
WAITING / TIMED_WAITING join(), wait(), LockSupport.park (incl. ReentrantLock), sleep
TERMINATED run() finished

2.1 How to run and how to wait

Choice Use when Don't use when
new Thread(...) demos, one background thread for the app's lifetime a thread per request
ExecutorService, framework pools most backend code you haven't thought about shutdown
Virtual threads many I/O-bound tasks heavy computation
Thread.sleep "to be safe" demos tests and real code: join(), CountDownLatch, Future.get(timeout)
interrupt() tasks that honor the interrupt flag tasks blocked on a classic socket: set timeouts, close the socket

2.2 Common traps

  • run() runs on the current thread: results are right, only parallelism is lost. The sign: the thread name prints main.
  • getState() right after start() isn't guaranteed to be RUNNABLE: the new thread may already be in sleep() or done.
  • sleep doesn't release held locks; wait() does.
  • Future.get() without a timeout hangs forever if the task hangs.

3. In Java

JAVA
Runnable task = () -> System.out.println("on " + Thread.currentThread().getName());
Thread t = new Thread(task, "worker-1");
t.run();    // "on main": no new thread
t.start();  // "on worker-1"; a second start() throws IllegalThreadStateException
 
public void run() {                                  // a correct worker loop
    while (!Thread.currentThread().isInterrupted()) {
        try {
            String job = queue.poll(1, TimeUnit.SECONDS);
            if (job != null) process(job);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();      // poll cleared the flag: restore it
            return;                                  // then actually stop
        }
    }
}
// shutdownNow() -> awaitTermination(2s) returns true

Other languages: Go can't stop a goroutine from outside, so pass a context.Context and check ctx.Done(); C# uses CancellationToken; Node.js uses AbortController.

Process, thread, concurrency, parallelism
Process Thread
Memory its own shared heap, own stack
Creation cost large smaller, still ~1 MB of stack + one OS thread
Communication IPC: sockets, pipes, files reading/writing shared heap objects

Concurrency is several tasks making progress interleaved; parallelism is several tasks running at once on several cores. More threads help with I/O waits; for computation, more than the core count is useless. In one JVM, each HTTP request is handled by a Tomcat thread.

4. Working with AI

Give the AI: shutdown tests for workers, summarizing a 500-thread dump into groups by state and stack.

Check in AI-written code:

  • No new Thread(...) on the request path.
  • Every catch (InterruptedException e) either rethrows or calls Thread.currentThread().interrupt().
  • No run() where parallelism was intended.
  • Tests don't wait with Thread.sleep.
  • Future.get() has a timeout; blocking I/O has a read timeout; threads are named.

5. Exercises

Exercise 1: A "clean shutdown" worker

The AI wrote a worker, described as "stops cleanly on shutdownNow()". The pod still always gets killed after 30 seconds.

JAVA
public void run() {
    while (true) {
        try {
            String job = queue.take();
            process(job);
        } catch (InterruptedException e) {
            log.warn("interrupted, continue");
        }
    }
}

Find the bug, name a test that proves it, and fix it.

Solution to Exercise 1
  • Bug: take() throws InterruptedException and clears the flag; the catch only logs and returns to while (true). The loop never checks the flag.
  • Test: submit the worker to newSingleThreadExecutor(), call shutdownNow(), assertTrue(pool.awaitTermination(2, SECONDS)): red with the current code.
  • Fix: the loop from section 3. If process(job) makes HTTP calls, set a read timeout, since interrupts can't cut a classic socket.

Exercise 2: Reading a thread dump

p99 went from 200 ms to 30 s, CPU at 4%. Thread dump: all 200/200 http-nio-8080-exec-* threads are RUNNABLE, with NioSocketImpl.read on top under a call to the payment service. A colleague says "200 threads are burning CPU, raise the pool to 400". Diagnose, the 15-minute action, the root fix.

Solution to Exercise 2
  • RUNNABLE includes threads blocked on I/O; 4% CPU means nobody is burning CPU. All 200 threads are waiting on the payment service.
  • Raising the pool only adds 200 more waiting threads and more load on the slow service.
  • 15 minutes: take 2–3 dumps a few seconds apart to confirm no progress, check the payment service's dashboard, enable a circuit breaker or fail fast on the payment flow.
  • Root fix: connect and read timeouts on the HTTP client, a limit on concurrent calls (bulkhead).

Summary

  • Write tasks as Runnable/Callable; only start() creates a new thread.
  • 6 states, no RUNNING; waiting on I/O is still RUNNABLE.
  • Threads stop cooperatively: interrupt() sets a flag, the task stops itself.
  • On InterruptedException: rethrow or restore the flag.
  • Synchronize with join, latches, Future.get(timeout), never sleep.

Read more: Race conditions, volatile, deadlocks.

Practice interview questions on this topic

All Concurrency questions →

Loading comments…