Open a chapter to study its implementation subtopics, worked examples and operational trade-offs. The overview below includes quick notes and interview practice.
The Java platform compiles source to bytecode and executes it on a compatible JVM.
Explanation:
Explain the separation between JDK tools, the runtime environment and the JVM. The JDK provides javac, java and development tools. javac emits class files, while the JVM uses class loaders, verifies bytecode and executes it by interpretation and JIT compilation. Bytecode can run on different operating systems when the JVM supports its class-file version and required APIs. Native libraries and filesystem behavior can still vary.
Primitives hold values; references identify objects or can be null. Scope says where a name is usable; lifetime concerns how long its storage or referent exists. Fields and array elements receive defaults; locals must be definitely assigned before use. Literal suffixes like L and F change the literal type. Use explicit numeric types when a boundary has a units or range contract.
Widening often needs no cast, but long to float may lose precision. Narrowing can discard high bits or a fractional part. Binary numeric promotion makes arithmetic on byte and short typically happen as int. Signed integer arithmetic wraps except operations such as division by zero. Promote before multiplying or use Math.multiplyExact; use BigDecimal constructed from text for exact decimal money.
Unboxing a null Integer throws. Wrapper identity can vary with caching; compare values using equals unless identity is intended. Java passes a copy of each argument value. Reassigning a reference parameter changes only that local copy; mutating its shared object can escape to the caller.
&& and || short-circuit; bitwise forms evaluate both sides. Use conditions, loops and explicit escape paths. Java 14 finalized switch expressions, available on 17 and 21. Arrays are fixed-size and covariant; storing a wrong runtime component type can throw ArrayStoreException. Multidimensional arrays are arrays of arrays and can be ragged. clone and Arrays.copyOf copy reference elements shallowly.
Imports shorten names; they do not import subpackages or override access. private, package access, protected and public establish different boundaries. JPMS adds module readability and exports or opens on top of Java access, so a public class can still be inaccessible outside its module.
Interview questions:
Where did overflow happen if the destination was long?
Before assignment. Both operands were int, so the multiplication was int arithmetic and only the already-overflowed value widened.
Object-oriented design groups state and behavior under lifecycle and ownership contracts.
Explanation:
Encapsulation protects invariants, abstraction exposes meaningful capabilities, and polymorphism lets implementations vary behind a contract. Inheritance is useful for true substitutability. Composition and delegation make collaborators replaceable without inheriting an entire implementation. Interface defaults can evolve behavior, but conflicts need an explicit resolution when neither default is more specific.
Illustration image:
Declared reference type · Selected signature · Actual receiver class · Overriding method
Example:
Worked example
record Batch(java.util.List<String> ids) {
Batch { ids = java.util.List.copyOf(ids); }
}
var input = new java.util.ArrayList<>(java.util.List.of("A"));
var snapshot = new Batch(input);
input.add("B");
System.out.println(snapshot.ids()); // [A], on Java 17 or 21
Overloading is chosen using compile-time types through strict invocation, boxing-compatible invocation and then varargs as applicable. Widening can win over boxing. null can make unrelated reference overloads ambiguous. Overridden instance methods dynamically dispatch using the receiver; fields and static methods are selected by declaration context. Covariant returns narrow the return type of an override.
Class initialization establishes superclass static state before subclass static initialization. Instance construction delegates with this or super; superclass construction runs before subclass instance field initializers and constructor body. An overridable method called from a constructor can see uninitialized subclass state. Do not publish this before the invariant holds. final prevents reassignment, overriding or subclassing depending on placement.
A static nested class has no enclosing instance. An inner class can retain the enclosing instance; local and anonymous classes can capture effectively final values. Enums model finite identities. Records describe component-based values, while sealed classes and interfaces constrain direct subtypes. A non-sealed permitted type reopens its branch.
Use private state, validate in constructors and copy mutable inputs and outputs according to ownership. A shallow copy duplicates the outer container, not its elements. A deep copy recursively isolates mutable state. A final List reference can still point at a mutable list; a record has shallow component immutability and may need a compact constructor.
Interview questions:
Why avoid calling an overridable method in a constructor?
Dynamic dispatch can reach subclass code before subclass fields are initialized. Keep construction behavior private or final and publish after construction.
Java value contracts define how objects compare, hash, represent text and encode time or numeric values.
Explanation:
Identity answers whether two references refer to one object. Equality answers whether they represent equal values under the type’s rules. Design a stable equality boundary before choosing a map key, comparator or serialization format.
var a = new java.math.BigDecimal("2.0");
var b = new java.math.BigDecimal("2.00");
System.out.println(a.equals(b)); // false
System.out.println(a.compareTo(b)); // 0
System.out.println("😃".length()); // 2 UTF-16 code units
System.out.println("😃".codePointCount(0, "😃".length())); // 1
getClass reports runtime type. toString should help diagnosis without leaking secrets. equals must be reflexive, symmetric, transitive, consistent and false for null. Equal values must share hashCode. A mutable hash key can become unfindable after insertion. Identity-based lookup is special-purpose and uses reference identity by design.
Comparable gives natural ordering. Comparator.comparing and thenComparing make sort keys explicit. If a comparator returns zero for unequal objects, a sorted set treats them as one ordering key. Compare numeric values with Integer.compare or comparingInt to avoid subtraction overflow.
String is immutable. Literals and constant string expressions may be interned; intern returns a canonical pooled string. Use equals for text. Prefer StringBuilder for repeated single-threaded appends, StringJoiner for delimiter-aware output, and understand that synchronized StringBuffer methods do not automatically make a multi-call sequence atomic.
A char stores one UTF-16 code unit. An emoji can require a surrogate pair, so String.length need not count code points or visible graphemes. Use codePoints for code-point logic and StandardCharsets.UTF_8 for explicit bytes. Do not truncate user-visible text by blindly cutting at a char boundary.
BigInteger handles arbitrary-precision integers; BigDecimal handles decimal scale and rounding. equals includes scale, compareTo compares numeric value. For time, Instant identifies a timeline point, LocalDate a calendar date and ZonedDateTime zone-aware local time. Period is calendar-based; Duration is elapsed time. Test DST gaps and overlaps and inject Clock for reproducible expiry rules.
Interview questions:
Why can TreeSet accept one BigDecimal while HashSet accepts two?
Natural ordering regards 2.0 and 2.00 as the same numeric value, while equals regards their different scales as distinct.
Exception handling propagates failures while resource management guarantees cleanup at an ownership boundary.
Explanation:
Design exception handling around recovery and ownership. Catch failures where a caller can retry, translate them across architectural boundaries or release resources. Preserve cause and useful diagnostic context while avoiding secret-bearing raw payloads in messages.
Illustration image:
Body throws · Resource B close fails · Resource A close fails · Primary with two suppressed
Example:
Worked example
try (java.io.BufferedReader reader = java.nio.file.Files.newBufferedReader(path,
java.nio.charset.StandardCharsets.UTF_8)) {
System.out.println(reader.readLine());
} catch (java.io.IOException failure) {
throw new java.io.UncheckedIOException("Could not read the input", failure);
}
Error typically indicates serious VM or environment conditions. Checked exceptions must be caught or declared. RuntimeException represents unchecked failures. throw raises an instance; throws declares part of a method contract. Catch narrower types before broader ones. Multi-catch alternatives cannot have a subtype relationship.
finally generally runs on normal and exceptional exit, but JVM termination can prevent it. Returning or throwing from finally can hide the earlier result or failure. Try-with-resources closes in reverse order; if the body throws and close also throws, the close failure is suppressed on the primary exception. Inspect getSuppressed during diagnosis.
Expose a domain-specific exception when a caller needs business context; pass the original cause. Propagate InterruptedException when possible. When a boundary cannot rethrow it, restore the interrupt flag with Thread.currentThread().interrupt() and leave promptly. Swallowing interruption can cause shutdown or cancellation to stall.
Interview questions:
What if reading fails and closing also fails?
Reading is the primary failure. The close failure is available from the primary exception’s suppressed exceptions, which remain attached to the cause after wrapping.
Generics express relationships between types and let the compiler reject incompatible uses.
Explanation:
Generics shift checks to compile time. A type parameter can express a dependency between multiple arguments and the return type. Use bounded type parameters only when implementation or callers need that bound. A generic method is often clearer than a generic class when the relationship belongs to one operation.
List<Integer> is not List<Number> because the latter would permit adding a Double. A List<? extends T> produces T values, while List<? super T> can consume T. Capture helpers give a name to an unknown wildcard when operations must preserve the same element type. Intersection bounds express several required capabilities.
The diamond operator derives type arguments from context. Erasure uses runtime bounds and compiler-inserted casts. A bridge method can preserve polymorphism after erasure. Raw types bypass checks and can hide a bad insertion until a distant read. Avoid unchecked casts unless an explicit runtime invariant justifies them.
Arrays carry a runtime component type; most generic type arguments are erased. This is why construction such as new List<String>[n] fails. Generic varargs create an array and can expose heap pollution if written through an unsafe alias or returned. @SafeVarargs is a promise about implementation behavior, not a runtime check.
Interview questions:
What can you safely read from List<? super Integer>?
Only Object under its declared type. You can safely write Integer values; the actual list may be a List<Number> or a List<Object>.
The Collections Framework supplies containers with distinct ordering, access and mutation contracts.
Explanation:
Choose a collection by its actual access pattern, not solely by an asymptotic label. Index access, memory locality, insertion order, duplicates, null policy and concurrency can matter as much as lookup cost.
ArrayList offers fast indexed access, amortized append and shifts on middle insertion. LinkedList needs traversal for positional access and allocates nodes. ArrayDeque efficiently serves queues and stacks and rejects null. PriorityQueue maintains a heap and exposes the next priority via peek or poll; its iterator is not sorted.
HashMap spreads hashes, indexes a bucket and checks key equality. Collisions may produce lists or tree bins under implementation thresholds. A resize redistributes entries when the load threshold is crossed. HashSet uses hash-key membership. LinkedHashSet and LinkedHashMap preserve defined order. Access-ordered LinkedHashMap moves entries when accessed, useful for a small local LRU policy.
TreeMap and TreeSet use red-black trees and support lower, floor, ceiling and higher operations and range views. Comparator equality determines uniqueness there. EnumSet packs enum members; EnumMap indexes enum keys. WeakHashMap uses weak keys and can change with GC; IdentityHashMap uses reference keys.
Use iterator.remove or supported list-iterator methods for safe structural mutation during traversal. Fail-fast is best effort. subList and Arrays.asList are backed views; the latter has fixed size. Unmodifiable wrappers reflect changes in the backing collection. List.of and List.copyOf are unmodifiable and reject null, but elements can still be mutable.
SequencedCollection, SequencedSet and SequencedMap express encounter order and operations at both ends. reversed returns a reverse-ordered view; it can reflect backing mutations. Sorting constraints or read-only implementations may reject end mutations even when exposing end reads.
Interview questions:
When is LinkedHashMap preferable to HashMap?
When insertion order or access order is part of the contract. For key sorting or nearest-key queries, use a navigable ordered map instead.
Streams express lazy pipelines, and Optional makes absence explicit at an API boundary.
Explanation:
Functional interfaces let a caller pass behavior. Predicate tests, Function transforms, Consumer performs an action and Supplier provides a value. UnaryOperator and BinaryOperator keep types aligned; primitive specializations avoid unnecessary boxing. Lambdas may capture final or effectively final locals and method references bind to a target functional signature.
Illustration image:
x, pear, plum · filter starts with p · map to length · findFirst gives 4
Example:
Worked example
var items = java.util.Arrays.asList("Pen", "Eraser", "Pen");
var counts = items.stream().collect(java.util.stream.Collectors.groupingBy(
java.util.function.Function.identity(),
java.util.LinkedHashMap::new,
java.util.stream.Collectors.counting()));
System.out.println(counts); // {Pen=2, Eraser=1}
compose applies the supplied function before this one; andThen applies it after. Predicate.and and or short-circuit. Stream intermediates run when a terminal operation drives traversal, and a stream is single-use. map maps one element to one result; flatMap flattens nested streams; mapMulti, available from 16, can emit multiple results without creating one stream per input.
filter tests, distinct de-duplicates, sorted imposes order, and skip or limit slice an encounter-ordered stream. Use reduce with an associative operation and neutral identity; use collect for mutable accumulation with independent partial containers and a combiner. Primitive streams provide specialized numeric terminals.
groupingBy uses a classifier, partitioningBy a Boolean predicate and counting yields Long. Add mapping or flatMapping (from 9) as downstream adapters. toMap needs a merge rule for valid duplicates. collectingAndThen applies a finishing step, joining assembles strings and summarizingInt supplies count, sum, min, max and average.
map wraps non-null output and flatMap composes Optional results. orElse evaluates eagerly; orElseGet builds a fallback lazily; orElseThrow makes absence explicit. A Spliterator describes how a source traverses or splits. Parallel streams pay split and coordination overhead; ordered or blocking work can bottleneck. Benchmark and keep effects outside stream internals.
Interview questions:
Why can reduce(10, Integer::sum) be wrong in parallel?
Ten is not the identity for addition. Each partition may start at ten. Reduce with zero and add ten once after the final result.
Java I/O converts, transfers and frames data across files, sockets and process boundaries.
Explanation:
Use byte streams for binary content and readers or writers for characters. A charset decoder transforms bytes into text. Buffering reduces small I/O calls, but still requires bounded processing for large input. Define protocol framing and timeouts independently from data conversion.
Illustration image:
Capacity 8 · put A: position 1 · flip: limit 1 · get reads A
Path and Files provide filesystem operations. Files.lines, list and walk can retain open resources and belong in try-with-resources. Buffers maintain position and limit; flip prepares written data for reading. Channels may support partial reads or writes. Selectors multiplex readiness for nonblocking selectable channels and the application remains responsible for framing and backpressure.
Separate connection establishment from read or request deadlines. Socket reads can return less than the requested length. HttpClient, standardized in 11, offers send and sendAsync. Check HTTP status and consume or close streaming bodies. Cancellation of a future does not universally undo the remote action. Preserve idempotency at the business boundary.
Serializable enables native object serialization. transient skips normal field serialization and serialVersionUID participates in compatibility. Deserialization filters constrain allowed shapes, depth or classes for legacy streams. For external boundaries prefer versioned formats with explicit schemas and validation. Treat parsing and authorization as different problems.
Interview questions:
Why avoid readAllLines for a multi-gigabyte log?
It materializes all decoded lines. Stream within a closed resource boundary and accumulate only the required result.
The JVM loads and executes Java code, manages application memory and exposes diagnostic evidence.
Explanation:
Class loading finds a definition, linking verifies and prepares it, and initialization runs static initializers before active use. Parent delegation avoids duplicate core types in conventional loaders. Class identity includes the defining loader. Two types with identical names can therefore be incompatible.
Illustration image:
Loader A defines Api · Loader B defines Api · Same binary name · Different class identities
Thread stacks contain frames for locals and operands. The heap holds objects, metaspace stores HotSpot class metadata, and direct buffers and thread stacks consume native memory. Interpretation starts execution and JIT compilation optimizes hot code. Inlining and escape analysis can remove call or allocation work; warm-up changes benchmark results.
GC starts from roots such as live stacks and static references. Strong references maintain reachability. Soft references can be cleared at collector discretion, weak references clear when weakly reachable and phantom references support post-mortem notification with a queue. Monitor allocation rate, live set, pauses and CPU overhead together.
Parallel GC prioritizes throughput. G1 balances regional collection with pause targets. ZGC minimizes pauses with different CPU and memory trade-offs; available variants depend on release. A StackOverflowError usually indicates excessive stack depth. OutOfMemoryError can concern heap, native allocation, direct buffers, metaspace or thread creation.
Compare retained objects, class loaders, caches, listeners and ThreadLocal lifetimes. A heap dump exposes retention but may affect production or contain confidential data. Use thread dumps for locks, GC logs for allocation and pauses, and JFR with Java Mission Control for time-series CPU and allocation evidence. Always compare before and after under matched load.
Interview questions:
Why can process memory grow while Java heap looks stable?
Metaspace, direct buffers, thread stacks, the JIT, allocator behavior and other native allocations can grow outside the heap.
Reflection inspects runtime types, while modules and release boundaries constrain accessible behavior.
Explanation:
Reflection inspects Class, constructors, methods and fields. Runtime discovery does not override language or module access rules. Metadata-driven frameworks should document what packages need exposure and why. Prefer stable public extension points when a migration would otherwise rely on internal JDK types.
module-info.java declares requires for dependencies, exports for public API packages and opens for deep reflection when allowed. Opening a package is broader than exporting it for normal calls. Diagnose compatibility with jdeps, runtime tests and a minimal reproducer before adding any scoped migration flag.
Java 8 brought lambdas, references, default methods, Streams, Optional, java.time and CompletableFuture. Java 9–17 brought modules, collection factories, var, standardized HTTP Client, switch expressions, text blocks, records, instanceof patterns and sealed types. Some features became final before 17; know the actual release when answering.
Java 21 finalizes virtual threads, record patterns, switch pattern matching and sequenced collections. Structured concurrency and scoped values are preview in Java 21. Build and run release-specific preview code with preview flags and distinguish these APIs from their status in later JDKs.
Interview questions:
Why can reflection fail on a public type after a migration?
The declaring package may not be readable, exported or open for the particular access. Check the module boundary and upgrade the library before adding a compatibility flag.
Threads execute concurrent work; interruption is a cooperative cancellation signal.
Explanation:
A process owns resources and address space. A platform thread maps to an OS thread in typical HotSpot deployments; the OS schedules runnable threads on CPU cores. A context switch changes which execution state runs. Thread implements execution of a Runnable, while Callable returns a value and can declare checked failures through an executor.
start schedules a new thread; calling run runs inline. NEW is unstarted, RUNNABLE covers eligible or executing work, BLOCKED means waiting to enter a monitor, WAITING is indefinite waiting, TIMED_WAITING is bounded waiting and TERMINATED is finished. A dump can show RUNNABLE in native I/O; use stacks and CPU samples to interpret it.
sleep does not release held monitors. wait requires ownership of its target monitor and releases that monitor while waiting. join waits for another thread's completion without releasing arbitrary locks held by the caller; avoid joining while holding locks that task needs. LockSupport.park does not release arbitrary locks and can return spuriously.
ThreadFactory centralizes naming and policy. Daemon threads do not keep the JVM alive, so do not rely on them for durable cleanup. An uncaught-exception handler sees uncaught thread failures; executor submit usually captures them in a Future, which must be observed separately.
interrupt sets a flag or wakes certain operations. isInterrupted reads without clearing; Thread.interrupted reads and clears the current flag. Future.cancel(true) requests interruption when supported but does not forcibly stop the work. A worker must respond, release resources and leave. Race, deadlock, livelock and starvation describe different failures; confinement avoids sharing mutable state in the first place.
Interview questions:
Why can cancel(true) return without releasing a database connection?
It requests cancellation; the task or driver still has to observe it and run cleanup. Use client timeouts and try-with-resources.
The Java Memory Model defines when writes by one thread are visible to another.
Explanation:
Atomicity concerns indivisibility, visibility concerns what another thread observes, and ordering concerns the allowed relation between actions. The Java Memory Model defines happens-before guarantees rather than promising the wall-clock interleaving you see in a debugger.
Unlock happens-before a subsequent lock of the same monitor. A volatile write happens-before subsequent reads of that field. Actions preceding Thread.start happen-before started-thread actions. Actions in a thread happen-before another observes termination through join. Use explicit coordination when conflicting accesses include a write.
A volatile shutdown flag can make the flag change visible. count++ reads, computes and writes, so two threads can lose an update even if count is volatile. Atomic counters or a lock can protect the operation. Reordering and stale reads are possible without a defined happens-before relationship.
Publish through static initialization, a lock, a volatile reference or a concurrent collection with a documented transfer edge. A normally constructed object's final fields have special initialization guarantees. Letting this escape can expose partial state. Safe publication establishes the initial view; later changes to mutable fields still need synchronization.
A volatile singleton reference is needed for correct double-checked locking. Simpler initialization-on-demand holders are often enough. Immutable snapshots can be built privately and swapped through a volatile or atomic reference; compare-and-set helps when several writers depend on the prior version.
Interview questions:
Why does a volatile array reference not make every element update volatile?
The volatile access applies to the reference. Mutations of array elements need a separate publication or synchronization strategy.
Locks protect shared invariants, and coordination primitives let threads wait for defined conditions.
Explanation:
Use a lock to protect an invariant, not merely a write. All code touching the invariant must agree on which lock protects it. Instance synchronized methods lock that instance and static synchronized methods lock its Class object. Java intrinsic monitors and ReentrantLock are reentrant, making nested acquisition by the same owner possible.
wait and notify require ownership. wait releases the monitor while suspended and reacquires it before returning. notify wakes one eligible waiter and notifyAll wakes all, but none can reconsider the condition until the notifier releases ownership. Use while because wakeups can be spurious or another thread can consume the condition first. Condition separates multiple queues such as notEmpty and notFull.
ReentrantLock supports tryLock, bounded acquisition and lockInterruptibly. Unlock in finally only after acquisition. ReentrantReadWriteLock allows concurrent readers and exclusive writers. Downgrade by acquiring read while holding write, then releasing write. An in-place read-to-write upgrade can deadlock. StampedLock is non-reentrant; read fields under an optimistic stamp, validate it and fall back to a read lock if invalid.
Choose lock granularity based on invariant scope and measured contention. Stripe independent keys but define consistent ordering for multi-lock operations. Fair locks can reduce overtaking with throughput cost and do not guarantee OS scheduling fairness. AQS supports state and waiter queues for many synchronizers. LockSupport supplies park/unpark permits; callers still need a condition loop.
Interview questions:
Why do you put wait inside while rather than if?
A wakeup only permits a new check. The guard may still be false or another worker may have consumed the available state.
Atomic operations update a shared value without exposing an intermediate state.
Explanation:
CAS updates only if the observed value still matches the expected one. Competing writers can force retries. ABA means a value changed away and came back between the initial read and CAS, which matters when the history carries meaning. AtomicStampedReference can include a version; AtomicMarkableReference includes a Boolean marker.
Illustration image:
A reads value 4 · B changes it to 5 · A CAS expects 4 · A retries from 5
Example:
Worked example
static boolean reserve(java.util.concurrent.atomic.AtomicInteger used, int limit) {
for (;;) {
int current = used.get();
if (current >= limit) return false;
if (used.compareAndSet(current, current + 1)) return true;
}
}
AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference target independent state. incrementAndGet returns the updated value and getAndIncrement returns the prior one. updateAndGet and accumulateAndGet may re-run their functions. Keep them side-effect-free; do not charge a payment or publish an event inside a retried transform.
LongAdder spreads increments across cells. Its sum is not an atomic snapshot during updates, so it works for metrics and is unsuitable for an exact concurrent quota. LongAccumulator applies an associative accumulation function with an identity. Use AtomicLong CAS for an exact admission limit and preserve counter bounds on release.
Atomic arrays and field updaters make specific elements or fields atomic. VarHandle adds access modes including acquire/release; use the matching access protocol deliberately. False sharing occurs when unrelated writes invalidate a shared cache line. Lock-free guarantees system-wide progress, while wait-free bounds each operation’s progress in its own steps; a CAS retry loop may starve.
Interview questions:
Why would checking LongAdder.sum before increment admit too many requests?
The check and increment are separate, and sum is not a linearizable snapshot. An exact check-and-reserve needs one coordinated operation.
Executors separate task submission from scheduling, concurrency and shutdown policies.
Explanation:
Executor schedules Runnable work. ExecutorService adds futures and lifecycle; ScheduledExecutorService adds delayed and periodic tasks. Callable can return a value and checked failure. execute submits fire-and-forget work; submit captures failures in a Future, so ignored futures can hide exceptions.
Illustration image:
Core slots · Bounded queue slots · Extra slots if full · Reject if all occupied
Example:
Worked example
var pool = new java.util.concurrent.ThreadPoolExecutor(
4, 8, 30, java.util.concurrent.TimeUnit.SECONDS,
new java.util.concurrent.ArrayBlockingQueue<>(32),
java.util.concurrent.Executors.defaultThreadFactory(),
new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
try {
pool.execute(() -> System.out.println("accepted"));
} finally {
pool.shutdown(); // accepted work is allowed to finish
}
ThreadPoolExecutor normally creates core workers first, then prefers enqueueing, then grows toward maximum when enqueueing fails, then rejects. An unbounded queue can prevent growth beyond core and hold unbounded work. Use bounded capacity, named threads, worker limits and documented overload behavior. Keep-alive applies to idle excess workers by default; core timeout can be enabled.
Fixed pools bound workers but their standard factory queues work without a capacity limit. Cached pools can create many workers. Single-threaded executors serialize tasks. Scheduled pools run delayed work. Work-stealing suits divide-and-conquer. Java 21 virtual-thread-per-task executors create a new virtual thread per task; limit the scarce backend separately.
AbortPolicy surfaces rejection; CallerRunsPolicy can slow the producer but may block a request or event-loop thread and discards work after shutdown. scheduleAtFixedRate targets a period; scheduleWithFixedDelay waits after completion. Uncaught exceptions suppress subsequent runs of that periodic task. On shutdown, stop admission, await a bounded drain, then attempt shutdownNow and inspect outstanding work.
CPU-bound work is constrained by cores. Blocking I/O needs concurrency sized around dependency latency and capacity. Isolate workloads with different failure modes. A task on a bounded executor should not synchronously wait for a child queued on the same saturated executor. Check queue age and completion rate, not just active count.
Interview questions:
Why does maximumPoolSize have no practical effect with an unbounded queue?
Once the core workers exist, enqueueing usually succeeds. The pool only tries to grow past core when enqueueing fails.
Completion stages represent asynchronous dependencies, while Fork/Join schedules divisible work.
Explanation:
Future models a pending result and supports blocking get and cancellation. CompletionStage models dependent work. CompletableFuture implements both. Use runAsync for side effects and supplyAsync for values. Choose an explicit executor for blocking I/O to protect common-pool workers.
Illustration image:
User lookup · User ID available · Order lookup · Extract status
Example:
Worked example
var profile = java.util.concurrent.CompletableFuture.supplyAsync(api::profile, ioPool);
var balance = java.util.concurrent.CompletableFuture.supplyAsync(api::balance, ioPool);
var overview = profile.thenCombine(balance, Overview::new)
.orTimeout(800, java.util.concurrent.TimeUnit.MILLISECONDS);
// Give the underlying API clients their own deadlines as well.
thenApply maps a value; thenCompose flattens a dependent asynchronous result; thenCombine merges two independent results. Non-Async continuations may run in the completing thread or the thread attaching a stage when already completed. Async variants without an executor generally use the common pool under ordinary configurations.
allOf waits for all stages, propagates exceptional completion, and returns no collected values. anyOf returns the first completion, which can be exceptional. exceptionally recovers on failure, handle transforms either outcome and whenComplete observes it. get reports checked failures; join wraps failures in unchecked CompletionException.
orTimeout and completeOnTimeout arrived in Java 9. The former completes exceptionally; the latter fills a fallback. Neither automatically interrupts network work. Keep deadlines at the client boundary and define whether partial results are legal. CompletableFuture.cancel uses exceptional completion; do not assume it drives a worker interrupt.
ForkJoinPool workers steal tasks. RecursiveTask produces a result and RecursiveAction has no value. Choose a split threshold large enough to amortize overhead. Blocking or shared mutable state can wipe out gains in parallel streams and contend with other users of the common pool. Compare with a sequential baseline under realistic load.
Interview questions:
Why can an Async continuation still compete with unrelated workloads?
Without an explicit executor it normally uses the default async facility. Other CompletableFutures or parallel streams can share that same pool.
Synchronizers coordinate progress, and thread-local state attaches data to a worker thread.
Explanation:
Choose a synchronizer by the protocol you want. A completion latch counts outcomes, a barrier waits for peers to reach a point, and a semaphore caps concurrent holders. They are not interchangeable just because all can block.
Illustration image:
Two registered tasks · Worker A counts down · Worker B counts down · Waiter continues
Example:
Worked example
var permits = new java.util.concurrent.Semaphore(4);
permits.acquire();
try {
callDatabase();
} finally {
permits.release();
}
CountDownLatch is one-shot; countDown in finally where the signal denotes termination, and track task errors separately. CyclicBarrier can rendezvous the same number of participants repeatedly; interruption or timeout can break a generation. Phaser supports dynamic registration and phases, making it useful for iterative work with changing participants. Deregister participants that exit.
Acquire a permit before touching a scarce resource and release only if acquisition succeeded. A semaphore does not track owner identity; releasing twice grows capacity incorrectly. Exchanger hands one value between two rendezvousing threads; use timeouts when a peer can disappear.
ThreadLocal attaches state to a thread, not a request. Pooled reuse can leak identity or keep old values alive. remove in finally. InheritableThreadLocal copies context at thread creation, so an existing executor worker will not inherit a new submission’s context. Capture immutable request metadata at submission and explicitly restore it with a supported logging or tracing integration.
Interview questions:
Why is release outside the protected acquisition unsafe?
On InterruptedException no permit was acquired. Releasing anyway increases available capacity beyond the intended cap.
Concurrent collections support shared access with documented atomicity, ordering and iteration guarantees.
Explanation:
A concurrent collection coordinates access to its own structure. It does not automatically guard mutable values stored inside it or make a sequence of separate calls atomic. Start by stating whether the invariant belongs to one key, several keys or an external system.
Illustration image:
Different keys can select the same bin. ConcurrentHashMap checks hash and equality inside the bin. The key-set view uses a shared TRUE value for membership.
Example:
Worked example
var exactPerKey = new java.util.concurrent.ConcurrentHashMap<String, Integer>();
exactPerKey.merge("pen", 1, Integer::sum);
var metrics = new java.util.concurrent.ConcurrentHashMap<String,
java.util.concurrent.atomic.LongAdder>();
metrics.computeIfAbsent("pen", key -> new java.util.concurrent.atomic.LongAdder())
.increment();
System.out.println(metrics.get("pen").sum()); // 1 after updates finish
Internal working:
ConcurrentHashMap internals and contracts
The Java 8+ OpenJDK implementation uses bins, CAS for some updates, bin-level synchronization under contention, tree bins for eligible heavy collisions and cooperative resizing. This is implementation context, not a promise callers should rely on. Keys and values cannot be null. Traversal is weakly consistent and can reflect some concurrent changes.
Atomic map methods and value safety
Use putIfAbsent, conditional remove, replace, compute, computeIfAbsent, computeIfPresent or merge for per-key updates. A containsKey then put races. Keep mapping functions short and avoid reentrant map updates. For mutable list values use immutable replacement, a concurrent value type or locking. A two-key balance transfer needs wider coordination.
Sets, ordered maps and snapshots
ConcurrentHashMap.newKeySet handles concurrent membership. CopyOnWriteArrayList and CopyOnWriteArraySet suit mostly-read listener registries; writes copy arrays and iterators are snapshots. ConcurrentSkipListMap and ConcurrentSkipListSet provide concurrent sorted or range operations with different performance than hash lookup.
Queue semantics and capacity
ConcurrentLinkedQueue and Deque are nonblocking, weakly consistent and have traversal-based size. BlockingQueue exposes add/remove with exceptions, immediate offer/poll, blocking put/take and timed offer/poll. ArrayBlockingQueue is fixed capacity with optional fairness. LinkedBlockingQueue and LinkedBlockingDeque can be bounded; default capacities may allow growth beyond safe memory budgets.
Specialized queues
PriorityBlockingQueue is logically unbounded and orders removals by priority, so explicitly break ties when needed. DelayQueue makes elements available when delays expire. SynchronousQueue provides direct handoff with zero storage. LinkedTransferQueue supports usual enqueueing and transfer that waits for receipt. Choose using backpressure and delivery semantics.
Wrappers, iterators and reductions
Synchronized wrappers need external locking on the wrapper during traversal or compound access. Distinguish fail-fast, snapshot and weakly consistent iterators. groupingByConcurrent and toConcurrentMap can reduce in parallel under their documented contracts; a ConcurrentHashMap of LongAdder works for contended frequency metrics. Its values still need key lifecycle and snapshot semantics.
Interview questions:
Why does a concurrent map of ArrayList values still fail under concurrent append?
The map coordinates finding or installing the list. The list’s own internal state is still shared without synchronization.
Virtual threads are JVM-scheduled Java threads introduced as a final feature in Java 21.
Explanation:
A virtual thread is a Java thread scheduled by the JVM onto a platform carrier. The OS schedules the carrier onto a CPU core. A supported blocking operation can unmount the virtual thread, so its carrier runs other work. A resumed virtual thread may use a different carrier.
Illustration image:
Virtual task A mounted · A awaits I/O · Carrier runs task B · A resumes
Example:
Worked example
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
var stores = new java.util.concurrent.Semaphore(4);
var result = executor.submit(() -> {
stores.acquire();
try { return fetchOrder(); }
finally { stores.release(); }
});
System.out.println(result.get());
}
In Java 21, blocking inside a synchronized region or certain native calls can pin a virtual thread to its carrier. Confirm impact with JFR or the JDK diagnostic before changing synchronization. Do not put heavyweight objects in per-thread state merely to reuse them across virtual requests; each task generally receives its own thread.
Use virtual threads when blocking APIs and straight-line code fit the system. CompletableFuture expresses dependency graphs; reactive pipelines express asynchronous streams and backpressure. Java 21 structured concurrency and scoped values are preview features: compile and run with the 21 preview flags and use the release-specific APIs.
Interview questions:
If virtual threads are cheap, why limit concurrency?
The database, heap and remote APIs remain finite. A bounded admission policy protects them and prevents arbitrarily many queued requests from exhausting memory.
Production diagnosis connects observed symptoms to evidence and checks recovery against invariants.
Explanation:
Diagnose by matching symptoms to evidence. A deadlock dump shows a wait cycle and lock owners; starvation can show queues stuck without a lock cycle. Queue growth adds waiting latency and retains tasks in memory. A hot CPU can mean useful work, a spin loop or a CAS hotspot; compare sampled stacks, throughput and JFR events rather than trusting thread state alone.
Illustration image:
Latency rises · Inspect queue age · Sample stacks and locks · Verify fix under load
Example:
Worked example
static void transfer(Account from, Account to, long amount) {
if (amount <= 0) throw new IllegalArgumentException("amount");
if (from == to) return;
// Account IDs are unique and immutable.
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) {
if (from.balance < amount) throw new IllegalStateException("insufficient");
long credited = Math.addExact(to.balance, amount);
from.balance -= amount;
to.balance = credited;
}
}
}
Use latches, barriers and bounded waits to make execution order intentional. Assert invariants rather than assuming a sleep reaches a particular state. Use JMH with warm-up, forks and meaningful result consumption. Keep setup distinct from measured work, record variability and measure on representative hardware and load.
Work through a bounded BlockingQueue and make producer and consumer shutdown coordinated. Avoid inserting a sentinel that can block indefinitely if the consumer stopped; define the drain and cancellation policy. Compare merge for exact per-key updates with LongAdder metrics under contention and verify final counts after workers join.
Acquire multiple account locks in a stable ID order and handle self-transfers. Never hold account locks while invoking another service. Start three independent calls before waiting, bound the overall deadline, and decide which failures permit partial responses. Client-specific deadlines and idempotency still matter.
Use a virtual thread per request and a semaphore or connection pool for downstream capacity. When caching, deduplicate in-flight loads by key using an installed Future or library support. Remove a failed in-flight result conditionally so it cannot remove a newer load, then apply bounded retries or a short failure TTL when appropriate.
Interview questions:
How would you test two opposing transfers?
Use a latch to release both workers, use deadline-bounded joins and assert completion, conservation of total balance, and nonnegative balances.
The JIT can compile frequently executed methods to native instructions at runtime.
The JDK provides the compiler and other development tools. javac checks source code against the Java language rules and emits bytecode. At runtime a class loader locates a class definition. Linking verifies bytecode, prepares static storage and resolves symbolic references, potentially lazily. Initialization executes static field initializers and static blocks before active use, such as invoking a static method.
A class is identified by its binary name and defining class loader. Two loaders can define classes with the same name and still produce incompatible types. The JVM may interpret bytecode and compile hot methods to machine code. Use javap -c to inspect bytecode and -Xlog:class+load=info on modern JDKs to trace class loading.
Example
javac -d out Hello.java
javap -c -classpath out Hello
java -Xlog:class+load=info -cp out Hello
Why might reading a static final primitive constant skip class initialization?
A compile-time constant can be inlined into the caller. The caller then uses a literal without triggering active use of the declaring class.
Java has eight primitive types and reference types. A reference variable holds a reference value or null. Widening conversions can lose precision when converting an integer to a floating-point type. Narrowing conversions require a cast in many contexts and can discard information. Integer division truncates toward zero. Use parentheses when precedence could obscure intent.
Arrays have fixed length and perform bounds checks. Reference arrays are covariant and check component compatibility at runtime. Use loop invariants to reason about traversal: before iteration i, a running total should describe elements 0 through i-1. Short-circuit && evaluates the right operand only when the left operand is true.
Example
int[] prices = {90, 105, 120};
long total = 0;
for (int price : prices) {
if (price >= 100) total += price;
}
System.out.println(total); // 225
What does 100000 * 100000 assigned to long produce?
The multiplication occurs as int and overflows before the assignment. Use a long operand such as 100000L.
Java passes every argument by value. When the value is a reference, caller and callee can use their respective copies to reach the same object. Assigning a new reference to a parameter changes the local parameter. Mutating the shared object can be observed by the caller.
A constructor establishes invariants. A final reference prevents reassignment but still permits mutation through the reference if its object is mutable. Use defensive copies when taking ownership of mutable arguments. Avoid calling overridable methods in constructors because subclass state might still be uninitialized.
Example
static void append(List<String> items) {
items.add("Pen");
items = new ArrayList<>();
}
// The caller observes the added Pen.
Will assigning a new list inside reset(List<String> items) replace the caller’s list?
The parameter holds a local copy of the reference. To replace the caller’s value, return a new list and assign it in the caller.
Use interfaces to define behavior at a boundary and composition to assemble collaborators. Overload selection occurs at compile time using declared types. Overridden instance methods dispatch at runtime using the receiver’s actual type. Static methods are hidden and resolved using the type.
A subtype should preserve its parent contract. If an implementation throws for a required operation or weakens promised guarantees, callers lose substitutability. Default interface methods can evolve APIs. If unrelated interfaces supply conflicting defaults, the implementing class must resolve the conflict.
Example
interface Pricing { int fee(int amount); }
class FlatPricing implements Pricing {
public int fee(int amount) { return 10; }
}
Pricing pricing = new FlatPricing();
System.out.println(pricing.fee(200)); // 10
What happens when a Parent variable holds Child and calls an overridden method?
The compiler checks that Parent exposes the method. Runtime dispatch selects the Child override.
String instances are immutable. Compile-time string constants are interned. Use equals for content and == for reference identity. Repeated concatenation in a loop can allocate a fresh result each iteration. StringBuilder accumulates changes in a mutable buffer and is appropriate for a thread-confined construction operation.
Autoboxing converts primitives to wrapper references. Identity comparisons between wrappers can give different results depending on cached instances. Unboxing a null Integer throws NullPointerException. For decimal money arithmetic, construct BigDecimal from decimal text and choose an explicit rounding policy.
A hash map uses a hash to narrow the search and equals to find the matching key. Equal objects must have equal hash codes. Unequal objects may collide. HashMap accepts a null key, supplies no iteration-order guarantee, and needs external coordination for concurrent structural mutation.
If fields used by equals and hashCode change after insertion, a subsequent lookup can search the wrong bucket. Make keys immutable. When a record contains a mutable collection, its generated equality and hash may still reflect mutations of that collection.
Example
record OrderKey(String customer, long orderId) {}
var orders = new java.util.HashMap<OrderKey, String>();
orders.put(new OrderKey("C1", 42), "PAID");
System.out.println(orders.get(new OrderKey("C1", 42)));
How do you release a lookup bug caused by previously persisted mutable key objects?
Rebuild the map using immutable snapshots of the keys. Test that mutations of the original input no longer affect lookup.
ArrayList offers indexed access and amortized constant-time append. LinkedList can unlink a node in constant time once the iterator is positioned, but locating an index requires traversal. ArrayDeque serves stack and queue workloads. HashSet tests membership with expected constant time given sound hash distribution, while TreeSet uses comparison order and logarithmic lookups.
Collections.unmodifiableList creates a read-only view backed by its source. List.copyOf creates an unmodifiable list representing the current elements but preserves references to those elements. Prefer the interface that expresses the contract. For order-sensitive systems specify the order explicitly and test it with duplicate or equal keys.
Example
var pending = new java.util.ArrayDeque<String>();
pending.addLast("order-1");
pending.addLast("order-2");
System.out.println(pending.removeFirst()); // order-1
Which map supports deterministic insertion-order iteration?
LinkedHashMap in its default insertion-order mode. TreeMap gives comparator order.
Generic parameters express compile-time constraints. List<Integer> is independent of List<Number> because List<Number> permits insertion of other Number subtypes. A List<? extends Number> can supply Number values. A List<? super Integer> can accept Integer values, and reads are only safely typed as Object.
Type erasure removes most generic type arguments at runtime. The compiler inserts casts where needed and can generate bridge methods to preserve polymorphism. Raw types bypass generic checks and can move type errors to runtime.
Example
static <T> void copy(java.util.List<? extends T> source,
java.util.List<? super T> target) {
for (T item : source) target.add(item);
}
Why can you read Number from a list of ? extends Number but cannot insert a Double?
The actual list might be List<Integer>. The bound guarantees the type of values read while leaving the concrete element type unknown.
Checked exceptions must be handled or declared. Unchecked exceptions include RuntimeException and its descendants. Catch exceptions where the program can recover or translate a failure into a meaningful boundary contract. Preserve the cause when translating.
Try-with-resources closes successfully opened resources in reverse declaration order. If the body throws and close also throws, the body exception remains primary, and close failures are available as suppressed exceptions. When a method catches InterruptedException and cannot rethrow it, restoring the interrupt flag can preserve cancellation intent.
Streams transfer bytes. Readers and writers bridge between bytes and characters using a charset. Specify UTF-8 when reading or writing a known format. Paths represent filesystem locations, and Files provides operations such as streaming lines, copying and creating temporary files.
Use buffered streaming for large inputs and close streams from Files.lines. For replacements write to a temp file in the same filesystem and consider an atomic move where supported. Atomic visibility and crash durability are separate properties. Test missing files, malformed text and partial writes at the boundary.
Happens-before edgeFor example, unlock then lock the same monitor
Thread B readsRead after acquiring the monitor
Visibility comes from ordering the accesses through the same synchronization mechanism.
Threads share heap objects and have separate call stacks. A data race occurs when conflicting accesses to the same location, including a write, lack a happens-before ordering. Synchronization establishes visibility and ordering through edges such as monitor unlock to a subsequent lock on the same monitor, or volatile write to a subsequent read of that field.
Volatile makes individual accesses visible under the memory model but count++ still reads, increments and writes separately. AtomicInteger provides atomic increments. Use a lock when a compound invariant spans multiple fields. Avoid holding a shared lock while waiting on a remote dependency.
Example
var counter = new java.util.concurrent.atomic.AtomicInteger();
Runnable request = () -> counter.incrementAndGet();
Does volatile int make count++ safe?
No. Two threads can read the same value and overwrite each other’s increments. Use incrementAndGet or synchronize the update.
An executor owns scheduling policy. Choose worker and queue bounds with the downstream service and latency budget in mind. Unbounded queues retain more work during overload and can grow even when worker count looks stable. Pick an explicit rejection policy and propagate a clear overload signal.
CompletableFuture composes asynchronous stages. thenCompose flattens a dependent asynchronous step, and thenCombine combines independent results. Provide an explicit executor for blocking work and apply timeouts at the I/O boundary. Timing out a future can leave its underlying task running.
Example
var pool = new java.util.concurrent.ThreadPoolExecutor(
4, 4, 0L, java.util.concurrent.TimeUnit.SECONDS,
new java.util.concurrent.ArrayBlockingQueue<>(100),
new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
try {
var task = pool.submit(() -> 42);
System.out.println(task.get(1, java.util.concurrent.TimeUnit.SECONDS));
} finally {
pool.shutdown();
}
What would you observe during a slow downstream incident?
Queue depth, rejection rate, active workers, dependency latency and request timeout rates reveal where work accumulates.
Stack frames hold local variables and operand stacks. Objects and arrays generally live on the heap from the application’s perspective. Modern JVM optimizations may avoid some allocations. HotSpot stores class metadata in native metaspace. GC identifies reachable objects from roots such as live thread references and loaded-class statics.
A Java memory leak often means objects remain reachable beyond their useful lifetime. Compare class histograms over time, inspect dominators and paths to GC roots, and correlate with allocation and GC telemetry. A high allocation rate can cause latency without increasing post-GC retained heap.
A cache grows after every deployment and heap usage remains high after GC. What do you inspect?
Inspect the retaining references and cache eviction limits. If old class loaders dominate memory, inspect retained threads, static caches and ThreadLocal values.
Annotations carry metadata. SOURCE retention is for compile-time processing, CLASS keeps metadata in bytecode, and RUNTIME exposes it to reflection. Reflection can inspect a class and invoke members dynamically, which frameworks use for component discovery and binding.
The Java module system distinguishes exports for public API access and opens for deep reflection. An accessible class can still contain private members that reflective callers cannot reach across module boundaries. Prefer a framework-compatible configuration that opens only the required package.
Example
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@interface Audited {}
@Audited class TransferService {}
// TransferService.class.isAnnotationPresent(Audited.class) is true.
What is the purpose of opens in module-info.java?
It permits deep reflective access to the specified package, optionally limited to named modules.
Enums declare a finite set of instances and can contain fields, constructors and behavior. EnumSet and EnumMap specialize collections for enum values. Use declared names or explicit stable codes when persisting a value. Ordinals change when constants are reordered.
A static nested class has no enclosing instance. An inner class can retain a reference to its enclosing object, which affects lifecycle if the inner instance is stored elsewhere. Prefer explicit dependencies when designing long-lived callbacks.
The method frame is popped on return. The object can remain reachable from the caller.
Imagine main calls createOrder(42). The JVM pushes a new frame for createOrder. The frame holds local values and temporary operands. The int argument is copied into the new frame. A newly constructed Order is represented as a heap object, and the local variable holds a reference to it. Returning that reference lets the caller keep the object reachable after the method frame is removed.
The reference and the object have different lifetimes. Recursion can exhaust a thread’s stack through excessive frames. Retaining too many Orders can exhaust the heap even with shallow stacks. Start with the actual exception and inspect the corresponding evidence: repeating stack frames for recursion and retained objects and GC roots for heap growth.
Example
record Order(long id) {}
static Order createOrder(long id) {
var order = new Order(id);
return order;
}
An Order is returned from a method. Can it be collected as soon as that method returns?
It remains reachable while a live reference can access it. Returning removes the method’s frame, but the caller receives a copy of the reference value.
Bucket selectionThe current table size narrows the search
Probe matching keysDistinct keys can share a bucket
Entry lookupA matching key returns its value
Two keys with the same hash can still be unequal. Equality decides whether they represent the same map key.
Two distinct keys can land in the same bucket. HashMap compares candidate keys using their hash and equality, so collisions do not merge different keys. In OpenJDK, a sufficiently large collision bin can convert to a tree when the table is large enough. This is an implementation detail; design keys with a stable, well-distributed hash and test against the public Map contract.
When the map grows beyond its resize threshold, operations can incur the cost of expanding its internal table and redistributing entries. Pre-size a map for a known large input only after considering memory and the target JDK. If a lookup key uses a mutable collection in equals and hashCode, changing that collection can make an existing mapping unreachable by normal lookup.
Example
record CustomerKey(String tenant, long id) {}
var cache = new java.util.HashMap<CustomerKey, String>();
cache.put(new CustomerKey("north", 42), "Active");
System.out.println(cache.get(new CustomerKey("north", 42))); // Active
How would you test a custom key before using it in a cache?
Create separate instances that should be equal, verify equal hashes and lookup using either instance, then verify changes to original mutable inputs cannot alter the key.
ConcurrentHashMap supports concurrent access, but a sequence such as get followed by put still leaves a race. Use merge, compute or putIfAbsent when the whole decision concerns one key. Keep remapping functions short and avoid remote calls while computing a map update. ConcurrentHashMap rejects null keys and values, so null from get represents absence.
An invariant spanning multiple keys needs a wider coordination mechanism. The success of a per-key update says nothing about a concurrent update to a second key. A concurrent map also lives inside one process. For cross-instance uniqueness, use a database constraint or another shared authority.
Example
var counts = new java.util.concurrent.ConcurrentHashMap<String, Long>();
counts.merge("order.created", 1L, Long::sum);
Why does a concurrent map still lose increments with get and put?
Two callers can read the same old count and each write the same next value. A single merge operation performs the update atomically for that key.
The last wait points back to the first holder. Both threads acquiring A before B breaks this cycle.
A monitor can serialize access to shared mutable state and establish visibility between threads. ReentrantLock offers explicit features such as interruptible acquisition and timed tryLock. Always release an acquired explicit lock in a finally block. Keep critical sections small and place blocking network work outside shared locks.
Deadlock occurs when threads wait in a cycle. For multiple account locks in a transfer, establish a consistent global acquisition order, such as ascending account ID, and handle source and destination equality. Capture a thread dump during a hang to distinguish a lock cycle from ordinary contention or waiting on I/O.
What happens if two methods protect the same fields using different monitor objects?
The methods can execute concurrently because they acquire different locks. Protect all accesses to the invariant with a consistent synchronization strategy.
thenApply maps a completed value. thenCompose chains a second operation that already returns a future, avoiding a nested future. thenCombine joins independently started work. Choose an explicit executor for blocking I/O and limit concurrency to protect downstream capacity.
orTimeout was added in Java 9. It can complete the future exceptionally without stopping an underlying network call. Configure connection and request timeouts at the client layer and decide when a partial result is acceptable. Test timeout, dependency errors and successful combinations independently.
How do you prevent a timed-out request from permanently occupying a worker thread?
Set time limits on the blocking client operation itself. Bound executor capacity and propagate cancellation only where the underlying task supports it.
A JDBC connection owns its transaction context. Disable auto-commit when several statements must commit together. Use prepared statements to bind values and inspect affected row counts for conditional updates. Try-with-resources closes statements and returns pooled connections when the connection is closed.
A connection pool limits how much work reaches the database at once. Pool acquisition delay, query duration and transaction duration answer different questions. A full pool can signal slow queries or long-held transactions. Increasing pool size can worsen contention, so measure before changing it.
Example
try (var connection = dataSource.getConnection();
var update = connection.prepareStatement(
"UPDATE inventory SET stock = stock - 1 WHERE id = ? AND stock > 0")) {
update.setLong(1, sku);
boolean reserved = update.executeUpdate() == 1;
}
An update returned zero rows. Should the application report success?
Only if its business contract permits a no-op. For a conditional stock decrement, zero rows means the reservation failed.