Scrivio Interview library

Threads

35 questions in 10 subtopics.

Thread lifecycle and states

ConceptFoundations5 min read
List the states of java.lang.Thread.State and give an action that moves a thread into each one.
CodingFoundations5 min read
What is the difference in behaviour here?
Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()));
t.run();
t.start();
DebuggingIntermediate7 min read
A thread dump of a slow service shows 300 threads in state RUNNABLE with the top frame in a socket read method, yet CPU usage is low. What does this mean and what would you check?
ConceptPrincipal7 min read
Java started with green threads on some platforms, moved to one Java thread per OS thread, added executors in Java 5, and added virtual threads in Java 21. Explain why each shift happened and what it tells you about choosing concurrency models for the next decade.

Runnable and Callable

ConceptFoundations6 min read
Compare Runnable and Callable, and explain how FutureTask relates to them.
DebuggingFoundations6 min read
A task fails but nothing is logged:
executor.submit(() -> {
process(order);
});
where process throws a RuntimeException. Explain why and give two fixes.

Daemon threads

ConceptFoundations6 min read
What is a daemon thread, how do you create one, and what happens to it when the JVM exits?
DebuggingIntermediate6 min read
A command-line batch job ends with exit code 0 but the last few hundred records are never written. Its main method calls CompletableFuture.runAsync(() -> writeBatch(batch)) for each batch and then returns. Explain and fix.
DesignAdvanced7 min read
Your shared libraries start background threads for metrics flushing, configuration refresh and connection cleanup in every service that uses them. Some services hang at shutdown and others lose final metrics. Define lifecycle standards for library-owned threads.

Interruption

ConceptFoundations6 min read
Explain how thread interruption works in Java, including the difference between Thread.interrupted() and isInterrupted().
CodingFoundations6 min read
What is wrong with this code and how would you fix it?
while (true) {
try {
Task t = queue.take();
handle(t);
} catch (InterruptedException e) {
log.warn("interrupted");
}
}
DebuggingIntermediate6 min read
During a rolling deploy, the application calls executor.shutdownNow() and awaitTermination(30, SECONDS), but awaitTermination returns false and some tasks keep running. List the reasons a task ignores interruption and how you would make tasks cancellable.
DesignAdvanced7 min read
Services in your platform call each other in chains of three to five hops. When a user cancels or a gateway times out, downstream work keeps running for seconds and wastes capacity. Design a cancellation standard across services.
ConceptPrincipal6 min read
Thread.stop, suspend and resume were deprecated in Java 1.2, and since Java 20 Thread.stop throws UnsupportedOperationException. Why is cooperative cancellation the long-term model for Java, and what does it imply for system design?

Thread priorities

ConceptFoundations5 min read
What do Java thread priorities guarantee, and why should application code rarely use them?
ScenarioIntermediate6 min read
A nightly reconciliation job shares a thread pool with request processing and sometimes does not finish by morning. A teammate proposes setting the job's thread priority to MAX_PRIORITY. Explain why that is unlikely to work and what you would do.
ConceptPrincipal6 min read
Thread priorities, ThreadGroup and Thread.stop seemed useful in Java 1.0 but are now ignored, degraded or removed. What makes concurrency features age badly, and how would you evaluate newer ones such as virtual threads, scoped values and structured concurrency as multi-year bets?

ThreadLocal and InheritableThreadLocal

InternalsFoundations6 min read
How is ThreadLocal stored internally, and why can it leak memory in thread pools?
DebuggingFoundations6 min read
A servlet filter stores the current tenant id in a static ThreadLocal and clears it at the end of doFilter. Occasionally a request sees another customer's tenant id. Find the likely bug.
DebuggingIntermediate7 min read
A JSON service caches a 1 MB byte buffer per thread in a ThreadLocal to avoid allocation. After enabling virtual threads with one virtual thread per request, memory usage climbs sharply. Explain and fix.
ScenarioIntermediate6 min read
Your service puts a trace id and user id into SLF4J MDC, which is ThreadLocal-based. After moving work to @Async methods and CompletableFuture chains, logs from background work lack the ids or show wrong ones. Explain and fix, including why InheritableThreadLocal does not solve it.
DesignAdvanced6 min read
Tenant id, user identity, trace context and locale are propagated today through ThreadLocals in many services, with async code, reactive code and soon virtual threads mixed in. What standard for request context propagation would you set across the platform?
LeadershipPrincipal6 min read
Your organisation has used ThreadLocal for request context for about 15 years: security, tenant, transactions, logging MDC. Virtual threads and scoped values change the trade-offs. What multi-year plan would you set for request context?

Thread naming and uncaught exception handlers

CodingFoundations6 min read
Write a ThreadFactory for an order-processing pool that gives threads readable names and logs uncaught exceptions. Why does this matter?
ScenarioIntermediate6 min read
During an incident, a thread dump shows 900 threads named like pool-3-thread-17 and Thread-212, and nobody can tell which component created them. What would you change in the codebase and in operations?
LeadershipAdvanced6 min read
A production incident: a background thread that synchronised customer data died silently from an unchecked exception, and data stopped syncing for six hours before anyone noticed. You lead the incident review. What standards come out of it for all teams?

Creating and starting threads

CodingFoundations6 min read
Show four ways to create and start a thread in Java 25: extending Thread, passing a Runnable, the Thread.Builder API for platform and virtual threads, and an ExecutorService. Which would you use in application code, and why is calling run() instead of start() a bug?
DebuggingIntermediate8 min read
A service creates new Thread(() -> sendEmail(order)).start() for every order. Under a traffic spike it fails with 'java.lang.OutOfMemoryError: unable to create native thread' and the host becomes slow. Explain the failure and fix the design, including whether virtual threads help.
LeadershipAdvanced8 min read
Your codebase has many places that create threads directly: new Thread, Executors.newCachedThreadPool, custom thread factories, and @Async with defaults. With virtual threads available, what rules would you set for thread creation across the organisation?

Joining and waiting for threads

CodingFoundations7 min read
Start three worker threads that each process part of a list, and make the main thread wait for all of them, with a total time limit of 5 seconds. Show it with Thread.join, with CountDownLatch, and with ExecutorService.invokeAll. What happens if a worker throws?
DesignIntermediate8 min read
A request handler fans out to three downstream services in parallel and must return when all succeed, or fail fast when any fails, cancelling the rest, within 2 seconds. Compare CompletableFuture.allOf, ExecutorService.invokeAll and structured concurrency (StructuredTaskScope) for this.
LeadershipPrincipal7 min read
Java's way of waiting for concurrent work moved from wait/notify and join, to java.util.concurrent futures and latches, to CompletableFuture chains and reactive streams, and now to structured concurrency. What does this history teach about choosing concurrency abstractions for a large codebase?

Concurrency vs parallelism

ConceptFoundations6 min read
Explain the difference between concurrency and parallelism, with one Java example of each. Can a program be concurrent on a single CPU core, and can parallel streams speed up an I/O-bound task?
ScenarioIntermediate7 min read
A batch job processes 10 million records: each record needs a CPU-heavy transformation (about 1 ms) and a database write (about 5 ms of waiting). How would you structure the threads or executors, and how would you choose the sizes?
DesignAdvanced7 min read
Your platform runs both latency-sensitive APIs and heavy CPU analytics on the same Kubernetes nodes and JVMs. Teams use parallel streams, ForkJoinPool and large thread pools freely. How would you organise concurrency and parallelism so the workloads do not hurt each other?