Language-Level Concurrency and Multithreading Questions
Per-language and per-runtime concurrency: the threading and async APIs each language and platform provides (goroutines, channels, worker pools and pipelines in Go, threads, executors, ThreadPoolExecutor tuning and CompletableFuture in Java, Kotlin coroutines, dispatchers, Flow and structured concurrency, Swift GCD with queues and QoS, DispatchGroup, OperationQueue, actors and async/await, Android Handler/Looper, HandlerThread and thread pools, Flutter isolates, C++ std::thread and atomics, Python threads versus multiprocessing versus asyncio tasks, gather and graceful shutdown), each language's memory model and visibility guarantees (Java happens-before and volatile, C++11 memory orders such as relaxed, acquire and release, Objective-C and Swift atomic versus nonatomic), mobile main-thread rules and JNI thread attachment, cancellation and shutdown idioms, and the idioms for coordinating shared state safely in that language, including thread-safe caches, singletons and bounded queues. Also covers reproducing, testing and diagnosing races and deadlocks in a specific language or app, and migrating callback, GCD or thread-pool code to structured concurrency. Covers choosing and using a language's concurrency primitives correctly. Boundary: general synchronization theory, deadlock and lock-free algorithm internals, OS scheduling, database isolation levels, and callback or event-loop architecture are covered elsewhere.
Implement a graceful shutdown pattern for an asyncio-based HTTP server in Python: stop accepting new connections, allow in-flight requests to complete with a configurable timeout, cancel long-running background tasks, flush metrics, and then exit. Provide function outlines for signal handling and describe race conditions to watch for.
Sample Answer
Direct answer
On SIGTERM, flip a "shutting down" flag from the signal handler and then run five steps in a fixed order: (1) close the listening socket so no new connections arrive, (2) wait for in-flight requests up to a configurable DRAIN_TIMEOUT, (3) cancel whatever is still running after that deadline and wait for it to unwind, (4) cancel the long-running background tasks, (5) flush metrics last, when nothing can change them any more, then return from asyncio.run so the process exits with code 0. The order matters: background tasks and metrics are used by requests, so they go after the requests, and the signal handler must only set a flag, not do the work.
Terms used here: SIGTERM is the signal an orchestrator (Kubernetes, systemd) sends to ask a process to stop, followed later by an unstoppable SIGKILL; draining means finishing work already accepted while refusing new work; the event loop is asyncio's single-threaded scheduler; a task is a coroutine the loop is running; cancellation raises CancelledError inside a task at its next await.
The server
This is a self-contained asyncio server (standard library only, so nothing to install) that answers GET /fast after 0.2 s and GET /slow after 3 s. It speaks HTTP by hand so that nothing hides the mechanics: an HTTP/1.1 request is a request line (GET /slow HTTP/1.1) followed by header lines and a blank line, so handle reads the first line, then reads and discards lines until the blank one. A response is a status line (HTTP/1.1 200 OK), headers (Content-Length tells the client how many body bytes follow, Connection: close says the connection ends afterwards), a blank line and the body. A framework does exactly this for you:
import asyncio, os, signal, sys
DRAIN_TIMEOUT = float(os.environ.get("DRAIN_TIMEOUT", "1.0")) # seconds allowed for in-flight requests
class App:
def __init__(self):
self.shutting_down = asyncio.Event()
self.inflight = set() # handler tasks currently serving a connection
self.background = [] # long-running tasks (metrics ticker, etc.)
self.metrics = {"served": 0, "aborted": 0}
async def handle(self, reader, writer):
task = asyncio.current_task()
self.inflight.add(task)
try:
if self.shutting_down.is_set(): # accepted just before the listener closed
writer.write(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
await writer.drain()
return
request_line = (await reader.readline()).decode().strip() # e.g. "GET /slow HTTP/1.1"
while (await reader.readline()) not in (b"\r\n", b"\n", b""):
pass # skip headers
delay = 3.0 if "/slow" in request_line else 0.2
await asyncio.sleep(delay) # pretend work
body = b"done\n"
hdr = b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" % len(body)
writer.write(hdr + body)
await writer.drain()
self.metrics["served"] += 1
except asyncio.CancelledError:
self.metrics["aborted"] += 1 # record, then let cancellation continue
raise
finally:
self.inflight.discard(task)
writer.close()
async def ticker(self):
try:
while True:
await asyncio.sleep(0.5) # periodic background job
except asyncio.CancelledError:
print("ticker: cancelled", flush=True)
raise
def request_shutdown(self, signame):
if self.shutting_down.is_set():
print(f"{signame} again: already shutting down", flush=True) # signals can arrive twice
return
print(f"{signame} received: starting shutdown", flush=True)
self.shutting_down.set()
async def run(self, port):
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, self.request_shutdown, sig.name)
server = await asyncio.start_server(self.handle, "127.0.0.1", port)
self.background.append(asyncio.create_task(self.ticker()))
print("listening", flush=True)
await self.shutting_down.wait()
# 1. stop accepting: close the listening socket. Existing connections stay open.
server.close()
print("step 1: listener closed", flush=True)
# 2. drain: wait for in-flight handlers, but only up to DRAIN_TIMEOUT.
deadline = loop.time() + DRAIN_TIMEOUT
while self.inflight and loop.time() < deadline:
await asyncio.wait(set(self.inflight), timeout=deadline - loop.time())
still = set(self.inflight)
print(f"step 2: drain over, still running {len(still)}", flush=True)
# 3. force: cancel what is left and wait for it to unwind.
for t in still:
t.cancel()
await asyncio.gather(*still, return_exceptions=True)
# 4. stop background tasks AFTER requests, since requests may still use them.
for t in self.background:
t.cancel()
await asyncio.gather(*self.background, return_exceptions=True)
# 5. flush metrics last, once nothing can change them.
print("step 5: flush metrics", self.metrics, flush=True)
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(App().run(int(sys.argv[1])))
Signal handling is loop.add_signal_handler, not signal.signal: the loop calls the handler on its own thread, between tasks, so the handler can safely touch asyncio objects. It only sets an Event (a flag that other tasks can wait on); the real work happens in run() after await self.shutting_down.wait() returns.
Proving it, with a driver
import asyncio, os, signal, subprocess, sys, time
async def get(port, path):
try:
r, w = await asyncio.open_connection("127.0.0.1", port)
except OSError as e:
return f"{path}: connection refused"
w.write(f"GET {path} HTTP/1.1\r\nHost: x\r\n\r\n".encode())
await w.drain()
data = await r.read()
w.close()
status = data.split(b"\r\n")[0].decode() if data else "closed with no response"
return f"{path}: {status}"
async def main():
port = 8765
p = subprocess.Popen([sys.executable, "server.py", str(port)], stdout=subprocess.PIPE, text=True,
env={**os.environ, "DRAIN_TIMEOUT": os.environ.get("DRAIN_TIMEOUT", "1.0")})
assert p.stdout.readline().strip() == "listening"
fast = asyncio.create_task(get(port, "/fast"))
slow = asyncio.create_task(get(port, "/slow"))
await asyncio.sleep(0.1) # both requests are now in flight
p.send_signal(signal.SIGTERM)
time.sleep(0.05); p.send_signal(signal.SIGTERM) # a second SIGTERM
await asyncio.sleep(0.2)
late = await get(port, "/late")
print("client:", await fast)
print("client:", await slow)
print("client:", late)
out, _ = p.communicate(timeout=10)
print("--- server log ---"); print(out.strip())
print("exit code:", p.returncode)
asyncio.run(main())
The driver (save it next to the server file, which must be named server.py because the driver launches it by that name) starts the server, opens /fast and /slow requests, sends SIGTERM twice (a second signal is a common real event), then tries a new connection. Run in a python:3.12-slim container (Python 3.12.15) with the default 1 second drain timeout, it printed (output order of client lines is deterministic; the server log is the child's own stdout):
client: /fast: HTTP/1.1 200 OK
client: /slow: closed with no response
client: /late: connection refused
--- server log ---
SIGTERM received: starting shutdown
step 1: listener closed
SIGTERM again: already shutting down
step 2: drain over, still running 1
ticker: cancelled
step 5: flush metrics {'served': 1, 'aborted': 1}
exit code: 0
Repeated five times, the metrics line 'served': 1, 'aborted': 1 appeared every time. With DRAIN_TIMEOUT=5 (enough for the 3-second request) the same driver printed /slow: HTTP/1.1 200 OK, still running 0 and {'served': 2, 'aborted': 0}. So the fast request finished, the late connection was refused, the slow request was cut off when the timeout expired and was counted, the background ticker was cancelled, metrics reflect the final state, and the exit code was 0.
The timeline of that run, with times measured from the first SIGTERM: at 0 s two requests are in flight, /fast (due at 0.2 s) and /slow (due at 3 s); the listener closes at once, so the later /late connection is refused. The deadline is 0 s + 1.0 s = 1.0 s. /fast finishes at 0.2 s and leaves inflight. The drain loop keeps waiting for /slow until the deadline, finds it still running, cancels it (its except asyncio.CancelledError counts it as aborted), and the process moves on to steps 4 and 5.
Choosing the timeout
Set DRAIN_TIMEOUT below the platform's kill deadline. Kubernetes, for example, sends SIGKILL after terminationGracePeriodSeconds (the pod setting for how long it waits between SIGTERM and SIGKILL; 30 s by default), so a 25 s drain leaves time for steps 3 to 5. If requests must be allowed longer than that, raise the grace period in the deployment rather than the app timeout alone.
Race conditions to watch for
- Signal arrives twice. Because the handler only sets an
Event, a second SIGTERM is harmless: setting an already-set event changes nothing, and the shutdown sequence inrun()executes exactly once. Theis_set()check only keeps the log from announcing a second shutdown. It would start to matter if the handler itself launched work, for example by creating a shutdown task, so keep the handler a flag-setter. - Connection accepted just before the listener closed. The loop may have accepted it and scheduled its handler task, but the handler has not run yet, so it is not in
inflight. Timeline: at 0 s the listener closes; a client's connection was accepted a moment earlier and its handler task exists but has not yet run, soinflightis empty; the drain conditionwhile self.inflight and ...is false at once, so step 2 waits for nothing and the sequence runs on to the metrics flush before that handler starts, perhaps 0.001 s later, and begins a request. The drain loop's re-read ofself.inflightdoes not close this gap: it picks up handlers that register while the loop is already waiting, not one that registers after the first empty check. What protects the late handler is the first branch ofhandle: once the flag is set it answers 503 immediately, so it does no real work and cannot outlive the drain deadline. With that branch removed, a late/slowrequest is served in full after the metrics line has been printed, and theservedcounter misses it. On Python 3.12,server.wait_closed()waits for active connections to finish (the documentation says it waits "until the close() method completes and all active connections have finished"), which is why the 503 is written before the process exits.asyncio.wait(tasks, timeout=...)returns when all the given tasks are done or the timeout passes (it does not raise for task errors), which is why the loop calls it again with a freshset(self.inflight)each time round: that picks up any handler that registered during the wait. - Cancelling a handler mid-write.
CancelledErrorcan arrive between a database commit and the response. Make writes idempotent (running the same request twice has the same effect as running it once, for example anINSERTkeyed by a client-supplied request id, so a retry after a cut-off is harmless) or finish them underasyncio.shield(which lets the inner commit run to completion even if the awaiting handler is cancelled, for exampleawait asyncio.shield(commit_order(order))). Shield alone is not enough at shutdown: once the handler is cancelled nobody awaits the inner task any more, andasyncio.runcancels every task still pending when it closes the loop, so a shielded commit that is still running at exit is cancelled too. Keep the shielded tasks in a set and await them, with their own timeout, in step 3 before moving on. - Swallowed cancellation. A handler that catches
Exceptionis fine (CancelledErrorderives fromBaseException, notException, since Python 3.8, soexcept Exceptiondoes not catch it and cancellation passes through), but a bareexcept:or atry/finallythat awaits forever blocksgatherin step 3. The server above records the abort and re-raises. - Ordering of steps 4 and 5. Cancelling the background tasks before the requests finish can break requests that call them; flushing metrics before the cancelled handlers update their counters loses data. The sequence in
run()avoids both. - Load balancer lag. Closing the listener stops new connections at this process, but a load balancer may keep routing for a few seconds. Fail the readiness probe first (a readiness probe is the health check the load balancer or Kubernetes calls to decide whether to send this instance traffic; flip a readiness flag in the same signal handler so it starts answering "not ready") and, if needed, sleep a short interval before step 1.
- Dependencies closed too early. Close database pools and HTTP clients after step 3, never before.
Verify a change with the driver: it fails visibly if the late connection is accepted, if the slow request is not counted, or if the exit code is not 0.
In Go, implement a concurrent worker pool that accepts tasks via a channel, supports N workers, applies backpressure when the queue is full, and supports graceful shutdown which stops accepting new tasks but finishes in-flight tasks. Provide function signatures and a sketch of key goroutine behavior (no need for full compiler-ready code).
Sample Answer
Direct answer
Use a buffered channel of tasks as the queue (a Go channel is a typed pipe between goroutines, the language's lightweight threads; a buffered one has a fixed capacity, a send succeeds immediately while there is room and blocks when the buffer is full, and a receive blocks while it is empty), N worker goroutines that range over it, and a Pool struct with three methods: Submit (blocks when the queue is full), TrySubmit (returns ErrQueueFull instead of waiting for queue space) and Shutdown (stops intake, drains, waits). The queue capacity is the backpressure: once it is full, the producer either waits or is told no, so memory cannot grow without bound. Graceful shutdown is close(tasks) after a flag stops new submissions: workers keep receiving until the channel is both closed and empty, so every accepted task still runs, and sync.WaitGroup tells Shutdown when the last worker has exited.
Signatures
type Task func()
type Pool struct { /* tasks chan Task; wg sync.WaitGroup; mu sync.RWMutex; closed bool */ }
func NewPool(n, queueSize int) *Pool
func (p *Pool) Submit(t Task) error // blocks while the queue is full; ErrClosed after Shutdown
func (p *Pool) TrySubmit(t Task) error // never waits for queue space; ErrQueueFull when full, ErrClosed after Shutdown
func (p *Pool) Shutdown() // stop accepting, finish queued and running tasks, then return
Goroutine behaviour
- Workers (N goroutines):
for t := range p.tasks { t() }, whererangeover a channel receives values one after another and ends when the channel is closed and empty. A receive from a closed channel only reports "done" once the buffer is empty, so closing the channel does not lose queued tasks.defer wg.Done()marks exit:deferschedules a call to run when the surrounding function returns, andsync.WaitGroupis a counter thatAdd(n)raises, eachDone()lowers, andWait()blocks until it reaches zero, soShutdownknows when every worker has exited. - Producers (any goroutine calling Submit): take a read lock, check
closed, then send. A full buffer blocks the send, which is the backpressure. Many producers can hold the read lock at once:sync.RWMutexallows any number of readers together but only one writer, and here the "readers" are the senders. They do not modify shared state; they only needclosedto stay false while they send. Using a plain mutex instead would make senders take turns, so one producer blocked on a full queue would hold up every other producer'sTrySubmitcheck, andShutdownis the only party that needs exclusive access. TrySubmit: the same check, then aselectwith adefaultcase.selectwaits on several channel operations and runs whichever can proceed; with adefaultcase it never waits on the channel, so if the send cannot proceed immediately (the buffer is full) thedefaultbranch runs and returnsErrQueueFull. It does still take the read lock first, and that lock can make it wait: ifShutdownis already waiting for the write lock because someSubmitis parked on a full queue, Go'ssync.RWMutexmakes new readers queue behind the waiting writer, so a freshTrySubmitwaits until the queue drains andShutdownhas taken and released the write lock, and then returnsErrClosed. The testTestTrySubmitWaitsBehindShutdown, shown after the stress test below, sets this up with one worker, a queue of one, one parkedSubmitand a pendingShutdown, and shows the newTrySubmitstill waiting until the worker is released.- Shutdown: takes the write lock (waits for in-progress sends to finish), sets
closed = true, callsclose(tasks)once, releases the lock, thenwg.Wait().
The lock exists for one reason: sending on a closed channel panics, and Go has no way to ask "is this channel closed?" atomically with the send. The read-write lock makes "check flag, then send" and "set flag, then close" mutually exclusive, so a producer can never send into a channel that Shutdown is closing.
Runnable code
package main
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
var (
ErrQueueFull = errors.New("queue full")
ErrClosed = errors.New("pool closed")
)
type Task func()
type Pool struct {
tasks chan Task
wg sync.WaitGroup
mu sync.RWMutex // makes "check closed, then send" exclusive with "set closed, then close"
closed bool
}
func NewPool(n, queueSize int) *Pool {
p := &Pool{tasks: make(chan Task, queueSize)}
p.wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer p.wg.Done()
for t := range p.tasks { // ends only when tasks is closed AND drained
t()
}
}()
}
return p
}
func (p *Pool) Submit(t Task) error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.closed {
return ErrClosed
}
p.tasks <- t
return nil
}
func (p *Pool) TrySubmit(t Task) error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.closed {
return ErrClosed
}
select {
case p.tasks <- t:
return nil
default:
return ErrQueueFull
}
}
func (p *Pool) Shutdown() {
p.mu.Lock()
if !p.closed {
p.closed = true
close(p.tasks)
}
p.mu.Unlock()
p.wg.Wait()
}
func main() {
p := NewPool(2, 2)
var done atomic.Int32
release := make(chan struct{})
slow := func() { <-release; done.Add(1) } // blocks until `release` is closed
// 2 workers pick up 2 tasks, 2 more fill the queue; the 5th is rejected.
for i := 1; i <= 5; i++ {
time.Sleep(20 * time.Millisecond) // let a worker dequeue before the next submit
fmt.Printf("task %d: %v\n", i, p.TrySubmit(slow))
}
go func() { time.Sleep(100 * time.Millisecond); close(release) }()
p.Shutdown()
fmt.Println("completed after shutdown:", done.Load())
fmt.Println("submit after shutdown:", p.Submit(slow))
}
The program uses atomic.Int32 and atomic.Int64, which need Go 1.19 or later. Run with go run -race in a golang:1.23 container, it prints:
task 1: <nil>
task 2: <nil>
task 3: <nil>
task 4: <nil>
task 5: queue full
completed after shutdown: 4
submit after shutdown: pool closed
Two workers hold tasks 1 and 2 (blocked on release), tasks 3 and 4 fill the capacity-2 queue, task 5 is refused. The 20 ms sleeps are only there so the first two tasks are dequeued before the next submit; they make the demo's output stable and are not part of the pool. After release closes, all four accepted tasks finish before Shutdown returns, and a later submit gets ErrClosed.
A stress test checks the shutdown race itself: 8 producer goroutines call Submit 50 times each while the main goroutine calls Shutdown concurrently, repeated 200 times. It lives in pool_test.go next to the pool:
package main
import (
"sync"
"sync/atomic"
"testing"
)
func TestShutdownRacesWithSubmit(t *testing.T) {
for iter := 0; iter < 200; iter++ {
p := NewPool(4, 8)
var ran, accepted atomic.Int64
var producers sync.WaitGroup
for g := 0; g < 8; g++ {
producers.Add(1)
go func() {
defer producers.Done()
for i := 0; i < 50; i++ {
if err := p.Submit(func() { ran.Add(1) }); err == nil {
accepted.Add(1)
}
}
}()
}
p.Shutdown() // runs while producers are still submitting
producers.Wait()
if ran.Load() != accepted.Load() {
t.Fatalf("iteration %d: ran %d tasks but %d submits succeeded", iter, ran.Load(), accepted.Load())
}
}
}
Run with go test -race -count=1 in the golang:1.23 container, on one CPU and on several, it prints ok with no race reported. To confirm the test can fail, delete the RLock/RUnlock pair from Submit and TrySubmit: the same test then reports a data race. That equality is the graceful-shutdown property: accepted means it runs. (The check runs after producers.Wait(), so it does not by itself notice a Shutdown that returns before the workers finish; the program in main above does, because it prints the completed count immediately after Shutdown returns.) (After Shutdown starts, later Submit calls return ErrClosed and are not counted as accepted.) The equality check also catches a Shutdown that throws away queued tasks, but only when several CPUs let producers and workers interleave: on a single CPU such a bug can pass unnoticed, so run this test with more than one CPU available.
The TrySubmit behaviour described above is checked by a second test in the same package, in its own file such as wait_test.go:
package main
import (
"testing"
"time"
)
// A TrySubmit that starts while Shutdown is waiting for the write lock queues behind it.
func TestTrySubmitWaitsBehindShutdown(t *testing.T) {
p := NewPool(1, 1)
release := make(chan struct{})
block := func() { <-release }
p.Submit(block) // the single worker takes it and blocks
time.Sleep(20 * time.Millisecond)
p.Submit(block) // fills the queue of one
go p.Submit(block) // parks: the queue is full
time.Sleep(20 * time.Millisecond)
go p.Shutdown() // waits for the write lock, which waits for the parked Submit
time.Sleep(20 * time.Millisecond)
result := make(chan error, 1)
go func() { result <- p.TrySubmit(block) }()
select {
case err := <-result:
t.Fatalf("TrySubmit returned %v while Shutdown was pending", err)
case <-time.After(200 * time.Millisecond):
// still waiting, as described
}
close(release) // the worker drains the queue, the parked Submit finishes, Shutdown proceeds
if err := <-result; err != ErrClosed {
t.Fatalf("after release TrySubmit returned %v, want ErrClosed", err)
}
}
Run with go test -race -count=1 -run TestTrySubmitWaitsBehindShutdown, it passes on one CPU and on many. If TrySubmit skipped the read lock, the test fails with "TrySubmit returned queue full while Shutdown was pending", which confirms the test can fail.
Design choices and what would change them
- Block or reject? Blocking (
Submit) suits an internal pipeline where slowing the producer is the desired effect. Rejecting (TrySubmit) suits an HTTP handler, where you would rather return 429 or 503 quickly than hold a connection. Recommend exposing both and letting the caller choose; for a request path default toTrySubmit, and stop routing traffic to the instance (or stop callingSubmitfrom other paths) before callingShutdown, because aTrySubmitthat arrives whileShutdownis waiting on a parkedSubmitwaits too. - Queue size. The buffer only absorbs bursts. A queue of 1,000 with slow tasks just delays the 503 and adds latency; size it to a short burst (a small multiple of N), not to your memory.
- Shutdown can wait forever if a task never returns. In production add a deadline: run
Shutdownin a goroutine andselecton its completion channel versusctx.Done(), and pass acontext.Contextinto tasks so they can be told to stop. Without it, one stuck task hangs a deploy. - A panic in a task kills the whole process, because it unwinds a worker goroutine with no recover. Wrap
t()in a function withdefer recover()and log, unless crashing is what you want. - Blocked
Submitcalls duringShutdownare allowed to complete:Shutdownwaits for the write lock, which waits for the blocked senders, who unblock as workers drain. That is correct for "finish what was accepted", but it means shutdown latency includes those producers, and anyTrySubmitthat starts in that window waits behindShutdownas well.
Write a concise C++ example in which two threads using relaxed atomic stores and loads reach a state that sequential consistency forbids, as can happen on weakly ordered hardware such as ARM. Then show the minimal change that makes it correct and explain why it works.
Sample Answer
Direct answer
The classic reordering bug is "message passing": a writer stores a payload, then raises a flag; a reader waits for the flag, then reads the payload. With every operation memory_order_relaxed, the reader can see the flag as 1 and the payload as 0, an outcome that sequential consistency (SC), the model where all operations appear to run in one agreed order that respects each thread's program order, forbids. The minimal fix is two arguments: make the flag store memory_order_release and the flag load memory_order_acquire.
Terms used here: a relaxed atomic operation guarantees only that the single operation is indivisible, with no ordering against other memory accesses; release on a store means every earlier read and write of that thread is visible to whoever reads that stored value with acquire; a weakly ordered CPU such as ARM may make two stores from one core visible to other cores in a different order than the program issued them.
The program
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
// Message passing: the writer stores data, then raises a flag.
// The reader spins until the flag is 1, then reads data.
// Sequential consistency forbids "flag seen as 1 but data seen as 0".
#ifdef FIXED
constexpr auto kStore = std::memory_order_release;
constexpr auto kLoad = std::memory_order_acquire;
#else
constexpr auto kStore = std::memory_order_relaxed;
constexpr auto kLoad = std::memory_order_relaxed;
#endif
struct Slot {
alignas(64) std::atomic<int> data{0};
alignas(64) std::atomic<int> flag{0};
};
int main() {
constexpr int kSlots = 200000, kPasses = 20;
std::vector<Slot> slots(kSlots);
long bad = 0;
for (int pass = 0; pass < kPasses; ++pass) {
for (auto& s : slots) { s.data.store(0); s.flag.store(0); }
std::thread writer([&] {
for (auto& s : slots) {
s.data.store(1, std::memory_order_relaxed);
s.flag.store(1, kStore);
}
});
long local = 0;
std::thread reader([&] {
for (auto& s : slots) {
while (s.flag.load(kLoad) == 0) {}
if (s.data.load(std::memory_order_relaxed) == 0) ++local;
}
});
writer.join(); reader.join();
bad += local;
}
std::printf("forbidden outcomes (flag==1 but data==0): %ld out of %d\n",
bad, kSlots * kPasses);
}
Each slot has its own data and flag. alignas(64) places each on its own 64-byte cache line (the unit in which cores copy and exchange memory), so the two stores travel through the memory system independently and the reorder has room to show up; if both sat on one line they would be exchanged between cores together and the reorder would be much harder to provoke. The data operations are atomic only so that the program has no undefined behaviour: the bug here is ordering, not tearing.
Compiled in a gcc:14 container (GCC 14.4, aarch64, 14 cores visible) with g++ -O2 -std=c++20 -pthread, and run at several CPU counts:
- Relaxed build: on the 14-core container the count out of 4,000,000 slots was nonzero and a different number each time; the count is not reproducible, only its presence, and with two CPUs a run can still print 0. It needs two cores running at the same time: with the container confined to one CPU (
--cpuset-cpus 0) the same binary printed 0, because the threads then take turns and their stores and loads never overlap. -DFIXEDbuild (release store, acquire load): every run printedforbidden outcomes (flag==1 but data==0): 0 out of 4000000.
Because the machine in that container is ARM (a weakly ordered CPU), the run shows what the hardware really does, not just what the language permits. A compiler may also reorder relaxed operations on any CPU, so the relaxed version is wrong everywhere even when a given machine happens not to show it.
Why the fix works
flag.store(1, release) forbids moving the earlier data.store after it. flag.load(acquire) forbids moving the later data.load before it. When the load reads the 1 that the store wrote, the two form a synchronizes-with edge: everything the writer did before the store, including data = 1, happens-before everything the reader does after the load. Seeing flag == 1 then implies seeing data == 1. On ARM the compiler turns the pair into store-release and load-acquire instructions (or barriers), which is exactly the extra work the relaxed version skipped. Nothing stronger than release/acquire is needed here, so seq_cst would only add cost.
A second reorder that release/acquire does not fix
Store buffering: thread A does x = 1; r1 = y; and thread B does y = 1; r2 = x;. SC forbids r1 == 0 && r2 == 0 because whichever store came first in the global order is visible to the other thread's load. Each thread's store may still be waiting in its core's store buffer (a small queue of pending writes) when the other thread's load runs, which is how both loads can return 0:
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
// Store buffering: A does x = 1; r1 = y. B does y = 1; r2 = x.
// Sequential consistency forbids r1 == 0 && r2 == 0.
#ifdef SEQCST
constexpr auto kOrder = std::memory_order_seq_cst;
#else
constexpr auto kOrder = std::memory_order_relaxed;
#endif
struct Slot {
alignas(64) std::atomic<int> x{0};
alignas(64) std::atomic<int> y{0};
int r1 = -1, r2 = -1; // each written by one thread only
};
std::atomic<int> arrived{0}; // lines the two threads up, round by round
int main() {
constexpr int kSlots = 200000;
std::vector<Slot> slots(kSlots);
auto lineUp = [](int round) {
arrived.fetch_add(1);
while (arrived.load() < 2 * (round + 1)) {}
};
std::thread a([&] {
for (int i = 0; i < kSlots; ++i) {
lineUp(i);
slots[i].x.store(1, kOrder);
slots[i].r1 = slots[i].y.load(kOrder);
}
});
std::thread b([&] {
for (int i = 0; i < kSlots; ++i) {
lineUp(i);
slots[i].y.store(1, kOrder);
slots[i].r2 = slots[i].x.load(kOrder);
}
});
a.join(); b.join();
long both_zero = 0;
for (auto& s : slots) if (s.r1 == 0 && s.r2 == 0) ++both_zero;
std::printf("r1==0 && r2==0 in %ld of %d rounds\n", both_zero, kSlots);
}
The lineUp helper makes the two threads start every round together, so their store and load really overlap; without it the threads drift apart and the outcome rarely appears. Compiled the same way in the gcc:14 container (aarch64) and run at several CPU counts per variant:
- All-relaxed: the count of the 200,000 rounds was nonzero on the 14-core container and a different number each time, and also with two CPUs. This also needs at least two CPUs: confined to one, the spin-wait in
lineUpmakes the program crawl instead of finishing promptly. -DSEQCST(seq_cston all four operations): every run printedr1==0 && r2==0 in 0 of 200000 rounds.- Release on the two stores and acquire on the two loads (edit
kOrderat those four operations): also 0 on every run on this aarch64 machine, because AArch64 implements release stores and acquire loads with store-release and load-acquire instructions (stlr/ldar) that are not reordered against each other. The C++ standard does not promise that result (it allows both threads to read 0 in this shape), and x86-64 hardware is allowed to show it: x86 lets a load complete before an earlier store to a different address is visible to other cores, and release/acquire compile to plainmovthere. No x86-64 result is shown here, so the aarch64 zero says nothing about x86. Portable code should useseq_csthere.
Example: a single-producer single-consumer ring buffer
A ring buffer (a fixed array used as a circular queue) with exactly one producer thread and one consumer thread needs release/acquire on its two indices and nothing stronger:
#include <atomic>
#include <cstdio>
#include <cstddef>
#include <thread>
// Single-producer single-consumer ring buffer. head is written only by the
// consumer, tail only by the producer. Capacity N-1 usable slots: one slot is
// always left empty so that head == tail can only mean "empty" and
// (tail + 1) % N == head can only mean "full".
template <typename T, size_t N>
class SpscRing {
T buf_[N];
alignas(64) std::atomic<size_t> head_{0}; // next slot to pop
alignas(64) std::atomic<size_t> tail_{0}; // next slot to push
public:
bool push(const T& v) { // producer thread only
size_t t = tail_.load(std::memory_order_relaxed); // own index
size_t next = (t + 1) % N;
if (next == head_.load(std::memory_order_acquire)) // consumer's progress
return false; // full
buf_[t] = v; // plain write
tail_.store(next, std::memory_order_release); // publish the slot
return true;
}
bool pop(T& out) { // consumer thread only
size_t h = head_.load(std::memory_order_relaxed); // own index
if (h == tail_.load(std::memory_order_acquire)) // producer's progress
return false; // empty
out = buf_[h]; // plain read
head_.store((h + 1) % N, std::memory_order_release);// free the slot
return true;
}
};
int main() {
constexpr int kItems = 1000000;
static SpscRing<int, 1024> ring;
long long sum = 0;
int out_of_order = 0;
std::thread producer([&] {
for (int i = 1; i <= kItems; ++i)
while (!ring.push(i)) {}
});
std::thread consumer([&] {
int expect = 1, v;
while (expect <= kItems) {
if (ring.pop(v)) {
if (v != expect) ++out_of_order;
sum += v; ++expect;
}
}
});
producer.join(); consumer.join();
std::printf("sum=%lld expected=%lld out_of_order=%d\n", sum,
(long long)kItems * (kItems + 1) / 2, out_of_order);
}
% N wraps an index back to 0 after the last slot, which is what makes the array circular. The producer is full when advancing tail_ would land on head_ (it must not overwrite a slot the consumer has not read); the consumer is empty when head_ has caught up with tail_. The producer's release store of tail_ publishes the plain write to buf_[t]; the consumer's acquire load of tail_ makes it visible. The consumer's release store of head_ tells the producer a slot may be reused, and the producer's acquire load of head_ ensures the consumer finished reading it first. Each side reads its own index with relaxed because no other thread writes it. Built with -fsanitize=thread and also with -O2, the program printed sum=500000500000 expected=500000500000 out_of_order=0 both times, with no TSan report. Downgrade either index store (the tail_ store or the head_ store) to relaxed and the plain buf_ access becomes a data race that TSan flags and that can lose or corrupt items on ARM. The design is only valid for exactly one producer and one consumer; with more threads the index updates need compare-and-swap loops (retry loops that read the index, compute the new value, and write it only if no other thread changed it in between) and a different design.
Compare the common ways to implement a thread-safe singleton in Java, including eager initialization, synchronized accessors, double-checked locking and a lazy holder class. Provide code for the one you would choose and explain why it is thread-safe.
Sample Answer
Direct answer
Choose the lazy holder class (also called the initialization-on-demand holder): a private static nested class whose only job is to hold the instance in a static final field. It is lazy, needs no synchronized and no volatile in your code, and its thread safety comes from a guarantee the JVM already gives for every class. If the singleton has no heavy construction cost, the even simpler eager version is equally correct. Reach for double-checked locking only when you cannot use a class-level holder (for example the instance needs a runtime argument or can be reset).
The four options
Two terms used below: to publish an object means to make a reference to it reachable by other threads, and it is published safely when those threads are guaranteed to see the object fully constructed, not half-built. Visible means a write made by one thread is guaranteed to be seen by another. Eager and the lazy holder need no locking code of your own; the synchronized accessor and double-checked locking do.
// 1. Eager
class Eager {
private static final Eager INSTANCE = new Eager();
private Eager() {}
static Eager get() { return INSTANCE; }
}
// 2. Synchronized accessor
class Synchronized {
private static Synchronized instance;
private Synchronized() {}
static synchronized Synchronized get() {
if (instance == null) instance = new Synchronized();
return instance;
}
}
// 3. Double-checked locking (needs volatile)
class DoubleChecked {
private static volatile DoubleChecked instance;
private DoubleChecked() {}
static DoubleChecked get() {
DoubleChecked local = instance; // one volatile read on the fast path
if (local == null) {
synchronized (DoubleChecked.class) {
local = instance;
if (local == null) instance = local = new DoubleChecked();
}
}
return local;
}
}
// 4. Lazy holder (the recommendation)
class Holder {
private Holder() { System.out.println("Holder constructed"); } // print only to show when construction happens
private static class Lazy { static final Holder INSTANCE = new Holder(); }
static Holder get() { return Lazy.INSTANCE; }
}
| Option | Lazy? | Cost per call after init | Thread-safety argument | Main drawback |
|---|---|---|---|---|
| Eager | no, built when the class is initialized | one static field read | class initialization is run once, under a lock, by the JVM | pays construction cost even if never used; construction failure surfaces at class load |
| Synchronized accessor | yes | lock acquire and release on every call | the monitor (Java's built-in lock) gives mutual exclusion and visibility | every caller contends on the lock forever |
| Double-checked locking | yes | one volatile read | volatile write publishes the object safely (see why below) | easy to get wrong; remove volatile and it is broken |
| Lazy holder | yes | one static field read | JVM class initialization lock, as for Eager, but triggered by the first get() | cannot take constructor arguments at call time |
A monitor is Java's built-in per-object lock (what synchronized acquires). "Class initialization" is the one-time step where the JVM runs a class's static initializers (the static field initializers and static { } blocks) before the class is first used.
Why the holder is thread-safe
The Java Language Specification (section 12.4.1) says a class is initialized immediately before the first invocation of one of its static methods, the first creation of an instance, or the first non-constant use of one of its static fields. Section 12.4.2 describes the initialization procedure: it takes a per-class initialization lock; if another thread is already initializing the class, the current thread blocks until that initialization completes. And the specification does not initialize a nested class merely because its outer class was initialized.
Put together for Holder:
- Loading
Holderdoes not build the instance, becauseLazyis a separate class that is not initialized yet. - The first call to
Holder.get()touchesLazy.INSTANCE, which triggersLazy's initialization. One thread runs the static initializer (which callsnew Holder()exactly once); every other thread that arrives meanwhile blocks on that class's initialization lock. - After initialization, the JVM does no further locking in your code: later calls are a plain read of a
static finalfield. The initialization procedure's lock hand-off is what makes the fully constructed object visible to threads that read the field afterwards.
Check it with this harness, saved as Check.java next to the four classes above (saved as Singletons.java), compiled with javac Singletons.java Check.java and run with java Check. It releases 16 threads together through a CyclicBarrier and counts distinct instances by identity. A deliberately broken lazy singleton with no lock is included as a control, so the harness is shown to be able to fail:
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
public class Check {
// Deliberately broken control: lazy creation with no lock at all.
static class Unsafe {
private static Unsafe instance;
private Unsafe() { try { Thread.sleep(1); } catch (InterruptedException e) { } }
static Unsafe get() { if (instance == null) instance = new Unsafe(); return instance; }
}
static int distinct(Supplier<Object> getter) throws Exception {
int n = 16;
CyclicBarrier barrier = new CyclicBarrier(n);
ExecutorService pool = Executors.newFixedThreadPool(n);
List<Future<Object>> results = new ArrayList<>();
for (int i = 0; i < n; i++)
results.add(pool.submit(() -> { barrier.await(); return getter.get(); }));
Set<Integer> ids = new HashSet<>();
for (Future<Object> f : results) ids.add(System.identityHashCode(f.get()));
pool.shutdown();
return ids.size();
}
public static void main(String[] args) throws Exception {
System.out.println("Before first use of Holder");
System.out.println("distinct instances: " + distinct(Holder::get));
System.out.println("eager " + distinct(Eager::get) + ", synchronized " + distinct(Synchronized::get)
+ ", double-checked " + distinct(DoubleChecked::get));
System.out.println("control (no lock) " + distinct(Unsafe::get));
}
}
Run in an eclipse-temurin:21-jdk container (OpenJDK 21.0.12), the first three lines were:
Before first use of Holder
Holder constructed
distinct instances: 1
The next line reported one distinct instance each for the eager, synchronized and double-checked versions, and the unlocked control reported more than one (the control's constructor sleeps 1 ms so the unsafe check-then-create window is wide), which is what shows the harness can fail.
The constructor line comes after the "before" line and appears once, so the first get() triggered construction, not loading of the outer class, and 16 racing callers still built one object. That output shows the property, it does not prove it, since a race that is rare would not show up in one test; the proof is the specification's lock.
Why double-checked locking needs volatile, in one paragraph
instance = new DoubleChecked() is several steps: allocate memory, run the constructor to fill in fields, then store the reference. Without volatile, the compiler or CPU may make the reference store visible before the field writes. One bad interleaving, with fields a = 42 set in the constructor:
- Thread A takes the lock, allocates the object and stores the reference into
instance. - Before A's write of
a = 42becomes visible, thread B runs the unlocked checkinstance == null, finds it non-null, skips the lock and returns the reference. - B reads
aand sees 0, the default, not 42.
So B can use a partly built object. (That is the failure to avoid; whether it appears on a given machine depends on the JIT compiler and CPU, and x86 rarely shows it while weaker-ordered CPUs such as ARM are more likely to.) Making the field volatile gives a happens-before edge (the guarantee that one action's effects are visible to another) from the write to every later read, which closes the hole (the full argument is its own topic in the Java Memory Model).
Other choices and their limits
- A single-element
enum(enum Config { INSTANCE; }) is also thread-safe by class initialization and additionally survives serialization and reflection attacks; use it when those matter. Serialization turns an object into bytes and back, and a normal class can come back as a second copy; reflection lets code call even a private constructor at runtime, which also creates a second copy. The language forbids both routes for enum constants, so the single instance cannot be duplicated that way. It also cannot extend a class. - If the singleton holds mutable state, thread-safe creation does not make its methods thread-safe. Protect that state separately.
- If tests need to replace the singleton, prefer passing the dependency in; static singletons make that hard.
- If construction can throw, the holder's
Lazyclass is left in an erroneous state (the JVM marks the class as failed to initialize) and the first call fails withExceptionInInitializerErrorwrapping the exception, and later calls fail withNoClassDefFoundError(JLS 12.4.2 step 5: a class whose earlier initialization failed is never initialized again, and the attempt throws that error) instead of retrying. Step 11 wraps only exceptions that are notErrors: a constructor that throws anErrorsuch asOutOfMemoryErrormakes the first call throw that error itself, unwrapped, and later calls still getNoClassDefFoundError. Run in the same JDK 21 container, a constructor that threwIllegalStateExceptiononce gaveExceptionInInitializerErrorand thenNoClassDefFoundError: Could not initialize class ...; one that threwOutOfMemoryErrorgave that error and then the sameNoClassDefFoundError. Use DCL or a supplier with explicit retry if construction can fail transiently.
In a multithreaded Java service, design an API for cancellable tasks. How would you propagate cancellation (interruption, Future.cancel, cooperative flags), ensure resource cleanup, and handle cancelling blocking I/O that does not respond to Thread.interrupt()?
Sample Answer
Direct answer
Java has no way to force a thread to stop, so cancellation is a request that the task honours at points where it can. Design the API around three layers and keep them separate:
- The request: the caller holds a
Future<T>and callscancel(true). That marks the future cancelled and, because oftrue, callsThread.interrupt()on the worker.cancelreturns immediately; it does not wait for the task to stop, and it returns false if the task already finished. - The signal inside the task: interruption is a flag on the thread. Blocking calls that are interruptible (
Thread.sleep,Object.wait,BlockingQueue.take,Lock.lockInterruptibly,Future.get, and NIO channel operations) throwInterruptedExceptionorClosedByInterruptException. (NIO is Java's "new I/O" package,java.nio, with channels and buffers;ClosedByInterruptExceptionis the exception a channel operation throws when its thread is interrupted, after the channel has been closed.) Tasks that compute in a loop must pollThread.currentThread().isInterrupted(), or a task-specific flag, themselves. - The cleanup: every resource the task opens is released in
try-with-resources(a Java block form that closes each declared resource automatically when the block exits, normally or by exception) orfinally, so cancellation, failure and success all go through the same exit path.
For blocking I/O that ignores interruption (a classic java.net.Socket read, shown below), interruption is not enough: the task must register a cancel hook that closes the thing it is blocked on, and the closing from another thread makes the blocked call throw. That hook is the fourth piece of the API.
Start with the first three layers: for most tasks, interruption plus try-with-resources is all that is needed. The hook is added only for a task blocked in a classic socket or stream read, and the timeout-polling and third-party cases in the table near the end are the fallbacks when neither interrupt nor close is available.
API shape
interface CancellableTask<T> extends Callable<T> {
void cancel(); // close whatever the task is blocked on
RunnableFuture<T> newTask(); // a Future whose cancel() also calls the hook
}
Rules the API enforces by convention and documentation:
- Cancellation is best effort and idempotent: (idempotent means doing it twice has the same effect as doing it once) calling it twice, or after completion, is harmless.
- A catch of
InterruptedExceptionmust not swallow it. Either rethrow, or callThread.currentThread().interrupt()to restore the flag, so the code above can still see the request. - Cancel can arrive before the task has registered its socket, in which case the hook closes nothing. A production version sets a cancelled flag in the hook and has the task check it right after
setSocket, closing immediately if set. - Always bound the wait: callers use
future.get(timeout, unit)and thencancel(true), not an unboundedget(). - Shutdown is the same idea one level up:
executor.shutdown()stops intake,awaitTermination(timeout)waits, andshutdownNow()interrupts the workers (so only cooperative tasks stop).
How the executor hook works
A plain Future.cancel(true) only interrupts the thread, which does nothing for a blocked socket read. The task therefore has to get a say when cancel is called. ThreadPoolExecutor.submit wraps every Callable in a RunnableFuture (the object that is both the runnable the pool executes and the Future the caller holds) by calling the protected method newTaskFor. The demonstration below overrides newTaskFor in a small executor subclass: if the callable is a CancellableTask, it asks the task to build its own FutureTask (the standard RunnableFuture implementation), and that one overrides cancel to call the task's hook as well. So when the caller does f.cancel(true), the sequence is: super.cancel(mayInterrupt) marks the future cancelled and interrupts the worker, then the hook closes the socket (unblocking the read with an exception). The future must be marked cancelled before the socket is closed: closing first lets the worker's read throw and finish the task exceptionally before the future is marked, so cancel could return false and the future would report a failure instead of a cancellation. That is a race, and with the two calls swapped the window is narrow: the demo below still printed true in repeated re-runs, but pausing 100 ms between the close and super.cancel made cancel(true) return false and isCancelled report false. Without the executor subclass, submit would build an ordinary FutureTask and the hook would never be called.
Runnable demonstration
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.concurrent.*;
public class Cancel {
interface CancellableTask<T> extends Callable<T> {
void cancel();
RunnableFuture<T> newTask();
}
static abstract class SocketTask<T> implements CancellableTask<T> {
private Socket socket;
protected synchronized void setSocket(Socket s) { socket = s; }
public synchronized void cancel() {
try { if (socket != null) socket.close(); } catch (IOException ignored) { }
}
public RunnableFuture<T> newTask() {
return new FutureTask<T>(this) {
@Override public boolean cancel(boolean mayInterrupt) {
boolean cancelled = super.cancel(mayInterrupt); // mark the future cancelled and interrupt the thread first
SocketTask.this.cancel(); // then unblock the socket read (never throws)
return cancelled;
}
};
}
}
static class CancellingExecutor extends ThreadPoolExecutor {
CancellingExecutor() { super(2, 2, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); }
@Override protected <T> RunnableFuture<T> newTaskFor(Callable<T> c) {
if (c instanceof CancellableTask<T> ct) return ct.newTask();
return super.newTaskFor(c);
}
}
static class ReadTask extends SocketTask<String> {
final int port; volatile boolean cleanedUp;
ReadTask(int port) { this.port = port; }
public String call() throws Exception {
try (Socket s = new Socket("127.0.0.1", port)) {
setSocket(s);
int b = s.getInputStream().read(); // blocks: the server never writes
return "read " + b;
} finally {
cleanedUp = true; // runs on every exit path
}
}
}
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(0)) {
int port = server.getLocalPort();
Thread acceptor = new Thread(() -> { // accepts and then stays silent
try { while (true) server.accept(); } catch (IOException ignored) { }
});
acceptor.setDaemon(true); acceptor.start();
// 1. Blocking socket read ignores interrupt.
Thread t = new Thread(() -> {
try (Socket s = new Socket("127.0.0.1", port)) { s.getInputStream().read(); }
catch (IOException e) { System.out.println("1. plain read ended with: " + e.getClass().getSimpleName()); }
});
t.start(); Thread.sleep(300);
t.interrupt(); t.join(500);
System.out.println("1. after interrupt(), thread alive: " + t.isAlive());
// 2. Task form: Future.cancel(true) marks the future cancelled and interrupts the worker, then closes the socket.
CancellingExecutor ex = new CancellingExecutor();
ReadTask task = new ReadTask(port);
Future<String> f = ex.submit(task);
Thread.sleep(300);
System.out.println("2. cancel(true) returned: " + f.cancel(true));
Thread.sleep(300);
System.out.println("2. cleaned up: " + task.cleanedUp + ", isCancelled: " + f.isCancelled());
// 3. Interruptible NIO channel: interrupt itself unblocks the read.
Thread nio = new Thread(() -> {
try (SocketChannel ch = SocketChannel.open(new InetSocketAddress("127.0.0.1", port))) {
ch.read(ByteBuffer.allocate(1));
} catch (IOException e) { System.out.println("3. NIO read ended with: " + e.getClass().getSimpleName()); }
});
nio.start(); Thread.sleep(300);
nio.interrupt(); nio.join(1000);
System.out.println("3. NIO thread alive: " + nio.isAlive());
// 4. Timeout polling: cooperative, needs no close.
Thread poll = new Thread(() -> {
try (Socket s = new Socket("127.0.0.1", port)) {
s.setSoTimeout(100);
while (!Thread.currentThread().isInterrupted()) {
try { s.getInputStream().read(); }
catch (SocketTimeoutException e) { /* loop and re-check the flag */ }
}
System.out.println("4. polling loop saw the interrupt flag and exited");
} catch (IOException e) { System.out.println("4. " + e); }
});
poll.start(); Thread.sleep(300);
poll.interrupt(); poll.join(1000);
System.out.println("4. alive: " + poll.isAlive());
ex.shutdownNow();
System.exit(0); // the plain thread in step 1 is still blocked and non-daemon
}
}
}
Run with java Cancel.java on OpenJDK 21.0.12.1 (container eclipse-temurin:21-jdk), it printed:
1. after interrupt(), thread alive: true
2. cancel(true) returned: true
2. cleaned up: true, isCancelled: true
3. NIO read ended with: ClosedByInterruptException
3. NIO thread alive: false
4. polling loop saw the interrupt flag and exited
4. alive: false
Reading it (a daemon thread is a background thread that does not keep the JVM alive; the acceptor is one, while the step 1 thread is not, which is why the program ends with System.exit):
- 1: interrupting a thread blocked in a classic socket read does nothing; the thread stayed alive (it is only freed by closing the socket or by the peer). The line
1. plain read ended with: ...in the code never prints, and that absence is the expected result: the read never throws, so thecatchblock never runs. - 2: the future was marked cancelled, the cancel hook then closed the socket, the read threw, the
finallyran (cleanedUptrue), and the future reports cancelled. The order matters:super.cancel(true)first, then close. - 3: NIO channels implement
InterruptibleChannel(the marker interface for channels that close themselves and throw when a thread blocked on them is interrupted): interrupting the thread closes the channel and the read throwsClosedByInterruptException. The channel is closed for good, so any other thread sharing it sees it closed too. - 4: setting a read timeout turns one long block into many short ones, and the loop checks the interrupt flag between them. This costs a wake-up per timeout interval (here 100 ms) and bounds the cancellation latency to that interval.
Choosing between the mechanisms
| Task is blocked in | Cancel with | Worst-case latency |
|---|---|---|
sleep, wait, BlockingQueue.take, Future.get | interrupt() (via cancel(true)) | immediate |
| NIO channel read or write | interrupt() closes the channel | immediate, channel is gone |
java.net.Socket read | close from another thread (the hook) | immediate, throws SocketException |
| CPU loop | poll the interrupt flag or a volatile boolean | one loop iteration; keep iterations short |
| Third-party call with no cancel API | per-call timeout, run in a separate bounded pool, accept the leak risk | the timeout |
Recommend: interrupt as the standard signal, a cancel hook on any task that holds a blocking socket or stream, try-with-resources for cleanup, and a timeout on every wait. Use a dedicated flag only for loops that never block. What would change it: if all I/O goes through NIO or an HTTP client with a built-in timeout and cancel, the hook can be dropped.
Unlock Full Question Bank
Get access to all 29 Language-Level Concurrency and Multithreading interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.