Java Materials
← All courses

Core Java

Senior interview preparation across Java 8, 17 and 21. Study the language first, then work through concurrency and production incidents.

Open the 15 new illustrated topics →

Open a chapter to study its implementation subtopics, worked examples and operational trade-offs. The overview below includes quick notes and interview practice.

Run the six JDK 21 concurrency labs ↗

Part I · Core Java

1. Platform and language fundamentals

Definition:

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.

Illustration image:

Platform and language fundamentals. Example.java · Example.class · invokespecial · Loaded class metadata · Executable main()Platform and language fundamentalsSource or actorExample.javaFirst boundaryExample.class · invokespecialInspected stateLoaded class metadataObservable effectExecutable main()
Example.java · Example.class · invokespecial · Loaded class metadata · Executable main()

Example:

Worked example
int unitPrice = 100_000;
long wrong = unitPrice * unitPrice;       // int multiplication overflows
long correct = (long) unitPrice * unitPrice;
Number[] covariant = new Integer[1];
// covariant[0] = 1.5;                     // ArrayStoreException
System.out.println(correct);             // 10000000000

Internal working:

  • Types and initialization

    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.

  • Conversions and overflow

    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.

  • Boxing and parameter passing

    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.

  • Control flow and arrays

    && 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.

  • Packages and access

    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.

2. Object-oriented design and lifecycle

Definition:

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:

Object-oriented design and lifecycle. Declared reference type · Selected signature · Actual receiver class · Overriding methodObject-oriented design and lifecycleSource or actorDeclared reference typeFirst boundarySelected signatureInspected stateActual receiver classObservable effectOverriding method
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

Internal working:

  • Dispatch and overloads

    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.

  • Initialization, this and super

    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.

  • Nested classes and domain types

    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.

  • Immutability and copying

    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.

3. Object contracts, strings and value types

Definition:

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.

Illustration image:

Object contracts, strings and value types. Key hash · HashMap bin · Equality check · Matching entryObject contracts, strings and value typesSource or actorKey hashFirst boundaryHashMap binInspected stateEquality checkObservable effectMatching entry
Key hash · HashMap bin · Equality check · Matching entry

Example:

Worked example
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

Internal working:

  • Object methods and hash keys

    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 and Comparator

    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.

  • Strings and joining

    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.

  • Unicode and encoding

    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.

  • Money and time

    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.

4. Exceptions and resource management

Definition:

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:

Exceptions and resource management. Body throws · Resource B close fails · Resource A close fails · Primary with two suppressedExceptions and resource managementSource or actorBody throwsFirst boundaryResource B close failsInspected stateResource A close failsObservable effectPrimary with two suppressed
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);
}

Internal working:

  • Throwable and propagation

    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 and suppressed failures

    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.

  • Translation and interruption

    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.

5. Generics and the type system

Definition:

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.

Illustration image:

Generics and the type system. List<Integer> source · Read as Integer · Append Integer · List<Number> targetGenerics and the type systemSource or actorList<Integer> sourceFirst boundaryRead as IntegerInspected stateAppend IntegerObservable effectList<Number> target
List<Integer> source · Read as Integer · Append Integer · List<Number> target

Example:

Worked example
static <T> void copy(java.util.List<? extends T> source,
                     java.util.List<? super T> target) {
    for (T item : source) target.add(item);
}
// Source List<Integer> can feed target List<Number>.

Internal working:

  • Invariance, PECS and capture

    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.

  • Inference and erasure

    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, varargs and heap pollution

    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>.

6. Collections Framework and internals

Definition:

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.

Illustration image:

Collections Framework and internals. ArrayList slots 0–3 · Middle insert shifts · ArrayDeque head/tail · Linked nodesCollections Framework and internalsSource or actorArrayList slots 0–3First boundaryMiddle insert shiftsInspected stateArrayDeque head/tailObservable effectLinked nodes
ArrayList slots 0–3 · Middle insert shifts · ArrayDeque head/tail · Linked nodes

Example:

Worked example
var queue = new java.util.PriorityQueue<>(java.util.List.of(7, 2, 5));
while (!queue.isEmpty()) System.out.print(queue.remove() + " "); // 2 5 7
var recent = new java.util.LinkedHashMap<String,Integer>(16, 0.75f, true);
recent.put("a", 1); recent.put("b", 2); recent.get("a");
System.out.println(recent.keySet()); // [b, a]

Internal working:

  • Lists, queues, deques and heaps

    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.

  • Hash-based collections

    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.

  • Sorted and specialized types

    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.

  • Iteration, views and immutability

    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.

  • Java 21 sequenced collections

    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.

7. Functional programming, streams and Optional

Definition:

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:

Functional programming, streams and Optional. x, pear, plum · filter starts with p · map to length · findFirst gives 4Functional programming, streams and OptionalSource or actorx, pear, plumFirst boundaryfilter starts with pInspected statemap to lengthObservable effectfindFirst gives 4
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}

Internal working:

  • Composition and laziness

    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.

  • Pipeline operations and reductions

    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.

  • Collector recipes

    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.

  • Optional and parallelism

    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.

8. I/O, NIO, networking and serialization

Definition:

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:

I/O, NIO, networking and serialization. Capacity 8 · put A: position 1 · flip: limit 1 · get reads AI/O, NIO, networking and serializationSource or actorCapacity 8First boundaryput A: position 1Inspected stateflip: limit 1Observable effectget reads A
Capacity 8 · put A: position 1 · flip: limit 1 · get reads A

Example:

Worked example
try (var rows = java.nio.file.Files.lines(path,
        java.nio.charset.StandardCharsets.UTF_8)) {
    long warnings = rows.filter(line -> line.startsWith("WARN")).count();
    System.out.println(warnings);
}

Internal working:

  • Paths and channels

    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.

  • Networking and HTTP

    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.

  • Serialization and wire formats

    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.

9. JVM internals, memory and diagnostics

Definition:

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:

JVM internals, memory and diagnostics. Loader A defines Api · Loader B defines Api · Same binary name · Different class identitiesJVM internals, memory and diagnosticsSource or actorLoader A defines ApiFirst boundaryLoader B defines ApiInspected stateSame binary nameObservable effectDifferent class identities
Loader A defines Api · Loader B defines Api · Same binary name · Different class identities

Example:

Worked example
jcmd PID Thread.print -l
jcmd PID GC.class_histogram
jcmd PID JFR.start name=core-java duration=60s filename=core-java.jfr
# With Native Memory Tracking enabled at JVM startup:
jcmd PID VM.native_memory summary

Internal working:

  • Memory and execution

    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.

  • Reachability and garbage collection

    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.

  • Collectors and failure classes

    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.

  • Leak and incident evidence

    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.

10. Reflection, modules and release coverage

Definition:

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.

Illustration image:

Reflection, modules and release coverage. Caller invokes interface · Generated proxy · InvocationHandler · Optional target callReflection, modules and release coverageSource or actorCaller invokes interfaceFirst boundaryGenerated proxyInspected stateInvocationHandlerObservable effectOptional target call
Caller invokes interface · Generated proxy · InvocationHandler · Optional target call

Example:

Worked example
module com.example.core {
    requires java.net.http;
    exports com.example.core.api;
    opens com.example.core.dto to com.example.framework;
    uses com.example.core.api.Parser;
}

Internal working:

  • Annotations, proxies and handles

    Retention controls whether metadata survives source, class-file or runtime boundaries; targets restrict location. Annotation processors run at compile time. Dynamic proxies dispatch interface calls through InvocationHandler. Method handles are typed callable references with explicit lookup permissions. ServiceLoader discovers declared service providers without hard-coded implementation names.

  • JPMS

    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 to 17

    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 18 to 21

    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.

Part II · Advanced multithreading and concurrency

11. Threads, lifecycle and cancellation

Definition:

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.

Illustration image:

Threads, lifecycle and cancellation. NEW · RUNNABLE · BLOCKED or WAITING · TERMINATEDThreads, lifecycle and cancellationSource or actorNEWFirst boundaryRUNNABLEInspected stateBLOCKED or WAITINGObservable effectTERMINATED
NEW · RUNNABLE · BLOCKED or WAITING · TERMINATED

Example:

Worked example
Thread worker = new Thread(() -> {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            process(queue.take()); // interruptible wait
        }
    } catch (InterruptedException cancelled) {
        Thread.currentThread().interrupt();
    }
}, "order-consumer");
worker.start();
worker.interrupt();
worker.join(1000); // check isAlive() to verify completion

Internal working:

  • Start, join and six states

    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.

  • Waiting and lock ownership

    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.

  • Names, daemon status and failure reporting

    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.

  • Cooperative cancellation

    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.

12. Java Memory Model and safe publication

Definition:

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.

Illustration image:

Java Memory Model and safe publication. Writer stores message · Volatile ready write · Reader observes ready · Reader sees messageJava Memory Model and safe publicationSource or actorWriter stores messageFirst boundaryVolatile ready writeInspected stateReader observes readyObservable effectReader sees message
Writer stores message · Volatile ready write · Reader observes ready · Reader sees message

Example:

Worked example
record Config(int timeoutMs, java.util.List<String> hosts) {
    Config { hosts = java.util.List.copyOf(hosts); }
}
class ConfigHolder {
    private volatile Config current = new Config(500, java.util.List.of("primary"));
    Config snapshot() { return current; }
    void replace(Config replacement) { current = java.util.Objects.requireNonNull(replacement); }
}

Internal working:

  • Happens-before edges

    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.

  • Volatile and compound operations

    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.

  • Publication and final fields

    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.

  • Double-checked locking and snapshots

    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.

13. Monitors, explicit locks and coordination

Definition:

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.

Illustration image:

Monitors, explicit locks and coordination. Consumer locks · Guard false · await releases lock · Reacquire and recheckMonitors, explicit locks and coordinationSource or actorConsumer locksFirst boundaryGuard falseInspected stateawait releases lockObservable effectReacquire and recheck
Consumer locks · Guard false · await releases lock · Reacquire and recheck

Example:

Worked example
final var lock = new java.util.concurrent.locks.ReentrantLock();
if (lock.tryLock(100, java.util.concurrent.TimeUnit.MILLISECONDS)) {
    try { updateSharedState(); }
    finally { lock.unlock(); }
} else {
    recordContention();
}

Internal working:

  • Guarded waits and conditions

    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.

  • Explicit and read/write locks

    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.

  • Fairness and low-level mechanics

    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.

14. Atomics and lock-free progress

Definition:

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:

Atomics and lock-free progress. A reads value 4 · B changes it to 5 · A CAS expects 4 · A retries from 5Atomics and lock-free progressSource or actorA reads value 4First boundaryB changes it to 5Inspected stateA CAS expects 4Observable effectA retries from 5
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;
    }
}

Internal working:

  • Atomic operations and functional retries

    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.

  • Contention and exactness

    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.

  • Low-level access and progress

    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.

15. Executors and thread-pool design

Definition:

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:

Executors and thread-pool design. Core slots · Bounded queue slots · Extra slots if full · Reject if all occupiedExecutors and thread-pool designSource or actorCore slotsFirst boundaryBounded queue slotsInspected stateExtra slots if fullObservable effectReject if all occupied
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
}

Internal working:

  • Admission, sizing and scheduling

    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.

  • Executor choices

    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.

  • Rejection and lifecycle

    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.

  • Starvation and capacity

    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.

16. CompletableFuture, Fork/Join and parallelism

Definition:

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:

CompletableFuture, Fork/Join and parallelism. User lookup · User ID available · Order lookup · Extract statusCompletableFuture, Fork/Join and parallelismSource or actorUser lookupFirst boundaryUser ID availableInspected stateOrder lookupObservable effectExtract status
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.

Internal working:

  • Composition and execution placement

    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.

  • Failure aggregation and completion

    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.

  • Timeout and cancellation semantics

    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.

  • Fork/Join and parallel streams

    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.

17. Synchronizers and thread-local state

Definition:

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:

Synchronizers and thread-local state. Two registered tasks · Worker A counts down · Worker B counts down · Waiter continuesSynchronizers and thread-local stateSource or actorTwo registered tasksFirst boundaryWorker A counts downInspected stateWorker B counts downObservable effectWaiter continues
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();
}

Internal working:

  • Latch, barrier and phaser

    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.

  • Semaphore and Exchanger

    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 and propagation

    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.

18. Concurrent collections

Open the illustrated deep dive and runnable examples →

Definition:

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. Hash spread → indexed bin → equalitypenspread hash∅0bin 11bin 22∅3pen = 2,000collisionCAS when bin is emptyCheck equality inside bin
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.

19. Java 21 virtual threads and preview concurrency

Definition:

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:

Java 21 virtual threads and preview concurrency. Virtual task A mounted · A awaits I/O · Carrier runs task B · A resumesJava 21 virtual threads and preview concurrencySource or actorVirtual task A mountedFirst boundaryA awaits I/OInspected stateCarrier runs task BObservable effectA resumes
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());
}

Internal working:

  • Creation and overload

    Thread.ofVirtual builds virtual threads; startVirtualThread starts one directly. Executors.newVirtualThreadPerTaskExecutor creates one per submitted task. Keep simple blocking code for high-concurrency I/O, but CPU-bound throughput remains limited by cores. Avoid pooling virtual threads to throttle them; bound database connections, remote quotas or concurrency instead.

  • Pinning and thread-local usage

    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.

  • Comparing models and preview features

    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.

20. Production diagnosis, testing and coding labs

Definition:

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:

Production diagnosis, testing and coding labs. Latency rises · Inspect queue age · Sample stacks and locks · Verify fix under loadProduction diagnosis, testing and coding labsSource or actorLatency risesFirst boundaryInspect queue ageInspected stateSample stacks and locksObservable effectVerify fix under load
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;
        }
    }
}

Internal working:

  • Testing and benchmarks

    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.

  • Producer–consumer and counters

    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.

  • Transfers and parallel APIs

    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.

  • Virtual-thread service and cache loading

    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.

Java Memory Model · Concurrency APIs · Virtual threads in Java 21 · Structured concurrency preview · Scoped values preview

Earlier examples and JDBC reference

JDK, bytecode and class loading

  1. Java sourceHello.java
  2. javacCompiles and type-checks
  3. Class filePortable bytecode
  4. JVMLoads, links and initializes
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.

Types, operators and control flow

  1. Input
  2. Type conversion
  3. Condition
  4. Result

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.

Objects, constructors and parameter passing

  1. Caller reference
  2. Copied reference
  3. Shared object

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.

Inheritance, interfaces and polymorphism

  1. Payment interface
  2. Card implementation
  3. Runtime dispatch

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.

Strings, wrappers and immutability

  1. Input text
  2. Immutable string
  3. Derived string

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.

Example
String input = "Java";
String upper = input.toUpperCase(java.util.Locale.ROOT);
System.out.println(input); // Java
System.out.println(upper); // JAVA
Why do some Integer values compare true with ==?

Boxing can reuse cached objects. Use equals for non-null value comparison or Objects.equals for nullable references.

Equality, HashMap and mutable keys

  1. Key
  2. Hash bucket
  3. Equality check
  4. Entry

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.

Collections and complexity

  1. Access pattern
  2. Pick collection
  3. Measure cost

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.

Generics and wildcards

  1. List of Integer
  2. Number producer
  3. Typed consumer

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.

Exceptions and resource lifecycles

  1. Acquire
  2. Use
  3. Close
  4. Report failure

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.

Example
static String firstLine(java.nio.file.Path path) throws java.io.IOException {
    try (var reader = java.nio.file.Files.newBufferedReader(path)) {
        return reader.readLine();
    }
}
Which exception wins if both resource use and close fail?

The exception from the body propagates, with the close failure attached as a suppressed exception.

I/O, NIO and encoding

  1. Bytes
  2. Charset decoder
  3. Characters
  4. Lines

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.

Example
try (var lines = java.nio.file.Files.lines(path,
        java.nio.charset.StandardCharsets.UTF_8)) {
    long errors = lines.filter(line -> line.startsWith("ERROR")).count();
    System.out.println(errors);
}
Why can readAllLines be a poor choice for a 4 GB log?

It loads all decoded lines into memory. Stream and process incrementally to bound retention.

Threads and the Java Memory Model

  1. Thread A writesUpdate shared data before release
  2. Happens-before edgeFor example, unlock then lock the same monitor
  3. 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.

Executors, futures and backpressure

  1. Requests
  2. Bounded queue
  3. Worker pool
  4. Dependency

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.

Heap, stacks, garbage collection and diagnostics

  1. GC roots
  2. Reachable objects
  3. Retained heap

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.

Example
jcmd PID GC.class_histogram
jcmd PID JFR.start name=profile duration=60s filename=profile.jfr
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, reflection and modules

  1. Class metadata
  2. Inspect members
  3. Check access

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, nested classes and object contracts

  1. Allowed states
  2. Enum value
  3. Domain operation

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.

Example
enum PaymentState { PENDING, CAPTURED, REFUNDED }
var completed = java.util.EnumSet.of(PaymentState.CAPTURED, PaymentState.REFUNDED);
Why might a non-static inner listener retain an entire service?

The listener instance can reference the enclosing service. A registry that retains the listener can thereby keep the service reachable.

JVM memory through a method call

  1. main framemain holds the caller’s locals
  2. Method framecreateOrder has its own locals
  3. Heap objectOrder(42) is referenced by order
  4. Return to callermain receives the reference
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.

HashMap collisions, resizing and key design

  1. Key hashHash comes from the lookup key
  2. Bucket selectionThe current table size narrows the search
  3. Probe matching keysDistinct keys can share a bucket
  4. 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 and atomic updates

  1. Incoming event
  2. Per-key computation
  3. Published value

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.

Locks, deadlocks and lock ordering

  1. Thread one holds AA is already acquired
  2. Waits for lock BThread one cannot continue
  3. Thread two holds BB is already acquired
  4. Waits for lock AThread two cannot continue
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.

Example
lock.lock();
try {
    balance = Math.addExact(balance, amount);
} finally {
    lock.unlock();
}
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.

CompletableFuture composition and failure budgets

  1. Start independent reads
  2. Combine results
  3. Apply deadline
  4. Surface failure

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.

Example
CompletableFuture<Profile> profile = CompletableFuture.supplyAsync(users::load, ioPool);
CompletableFuture<Balance> balance = CompletableFuture.supplyAsync(wallet::load, ioPool);
var summary = profile.thenCombine(balance, AccountSummary::new)
    .orTimeout(800, java.util.concurrent.TimeUnit.MILLISECONDS);
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.

JDBC transactions and connection pooling

  1. Borrow connection
  2. Bind parameters
  3. Update rows
  4. Commit and return connection

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.