JVM internals, collections, concurrency, streams and GC. Open a question to read the answer.
The JVM executes bytecode, the JRE is the JVM plus the standard class library needed to run programs, and the JDK is the JRE plus development tools (javac, jar, javadoc, jshell, jcmd, jlink). Since Java 11 Oracle and most vendors no longer ship a separate JRE download; you install a JDK and, if you want a trimmed runtime for deployment, build one with jlink from the modules your application actually uses.
The JVM is a specification (the JVM Specification) with several implementations: HotSpot (OpenJDK, the one almost everyone runs), OpenJ9 (Eclipse/IBM), and GraalVM, which adds an ahead-of-time native-image compiler. HotSpot interprets bytecode first, then its C1 and C2 JIT compilers compile hot methods to machine code at runtime, which is why warm Java code often runs close to native speed.
This diagram shows how the layers nest.

Bytecode is portable across operating systems; the JVM binary is platform-specific. That split is the “write once, run anywhere” promise, and it is also why a class compiled with Java 21 (class file version 65) refuses to load on a Java 17 runtime.
Apply. Pin one JDK vendor and LTS version (17, 21 or 25) across developer machines, CI and containers, typically through a .sdkmanrc or .tool-versions file plus a base image such as eclipse-temurin:21-jre. For production images I build a slim runtime with jlink --add-modules $(jdeps --print-module-deps app.jar) so the container carries only the modules the service needs, which cuts image size and attack surface. Compiler targets are set explicitly with --release 21 so nobody accidentally uses newer APIs.
Test. CI runs the build on every supported JDK (a matrix of 17 and 21, say) so library consumers on the older LTS are not broken. I also run a smoke test of the jlink image, because a missing module (commonly jdk.crypto.ec or java.sql) only fails at runtime.
Troubleshoot. UnsupportedClassFileVersionError (“class file version 65.0, this version only recognizes up to 61.0”) means a Java 21 build is running on a Java 17 JVM; java -version in the container usually reveals a wrong base image. ClassNotFoundException for a JDK class after jlink means a module was omitted. For startup or JIT problems I check java -XX:+PrintFlagsFinal -version to see what the JVM actually chose for heap and GC inside the container’s cgroup limits.
Mixing vendors is usually harmless, but GraalVM native-image or OpenJ9 behave differently enough (reflection configuration, GC options) that the choice must be deliberate, not accidental.
Java has exactly eight primitive types (boolean, byte, short, char, int, long, float, double); everything else, including arrays, String, enums, records, and boxed wrappers like Integer, is a reference type. A primitive variable holds the value itself; a reference variable holds a pointer to an object on the heap (or null).
Consequences that matter in practice:
== compares primitive values but compares identity for references; use equals for content.null and have defaults (0, false); reference fields default to null.int and Integer. Unboxing a null Integer throws NullPointerException.Integer.valueOf caches -128 to 127, so == on small boxed values happens to be true and fails for larger ones.List<Integer>, never List<int>), which is why primitive streams (IntStream) and specialised collections exist to avoid boxing overhead.Integer a = 127, b = 127, c = 1000, d = 1000;
System.out.println(a == b); // true (cached)
System.out.println(c == d); // false (different objects)
System.out.println(c.equals(d)); // true
int[] counts = new int[3]; // array is a reference; elements are 0Project Valhalla’s value classes (still in preview as of Java 25) aim to blur this line by letting user-defined types be flattened like primitives.
Apply. In a pricing engine I keep hot-path arithmetic on long cents or BigDecimal, never double, and avoid boxed types in tight loops: IntStream.range instead of Stream<Integer>, long[] instead of List<Long>, and Map<Long, X> only where a primitive-keyed library (Eclipse Collections, fastutil) is not justified. Domain fields that are optional become Integer / Long deliberately so null carries meaning; required numeric fields stay primitive so they can never be null.
Test. Unit tests cover the boundaries that boxing hides: equality of ids above 127, null coming from a JSON field mapped to int (Jackson fails fast with MismatchedInputException unless you allow it), and overflow with Math.addExact. A JMH benchmark on the hot loop shows whether boxing is actually costing anything before anyone rewrites code.
Troubleshoot. A NullPointerException at a line with no obvious dereference is almost always auto-unboxing (int x = map.get(key)); Java 14+ helpful NPE messages say so directly (“because the return value of Map.get is null”). An == comparison that works in tests and fails in production is the Integer cache. GC pressure from millions of short-lived Long objects shows up in JFR’s allocation profile, and the fix is a primitive array or specialised collection.
Boxed types in a HashMap key path are usually fine; it is the per-element allocation in large loops that hurts.
A String is immutable: its character array is private final and no method mutates it. Operations like toUpperCase or concat return new objects. Immutability makes strings safe to share across threads, safe as HashMap keys (the cached hash never goes stale), and safe for security-sensitive parameters such as class names and file paths.
Because they are immutable, the JVM can share them. String literals and compile-time constants are interned in the string pool, a JVM-managed hash table (on the heap since Java 7). Two literals "abc" therefore reference the same object, while new String("abc") or runtime concatenation creates a distinct object. String.intern() returns the pooled instance.
String a = "java";
String b = "ja" + "va"; // constant-folded, same pooled object
String c = new StringBuilder("ja").append("va").toString();
System.out.println(a == b); // true
System.out.println(a == c); // false
System.out.println(a == c.intern()); // true
System.out.println(a.equals(c)); // true (always compare with equals)Since Java 9, compact strings store Latin-1 text in one byte per character. Java 9 also replaced StringBuilder chains in + concatenation with invokedynamic, so loop concatenation is less wasteful than it once was, though StringBuilder is still right for building in a loop.
Apply. Immutability lets me pass strings into caches, log contexts and concurrent collections without defensive copies. In a log-ingestion service that parses millions of events with a small set of repeated values (status codes, service names), I deduplicate those values explicitly with a bounded ConcurrentHashMap interner (or Guava’s Interners) rather than String.intern(), whose fixed-size JVM table and native-method cost make it a poor general cache. For heavy building I use StringBuilder with a sized capacity; for text that must be wiped (passwords) I use char[], because a String stays in the heap until collected.
Test. Tests assert with assertEquals, never ==; a static-analysis rule (Error Prone StringEquality, SonarQube S4973) catches == on strings before review. A small JMH benchmark confirms the interner reduces allocation before I keep it.
Troubleshoot. A heap dump dominated by byte[] owned by String with thousands of identical values means duplicate strings; -XX:+UseStringDeduplication (G1, ZGC, Shenandoah, and Parallel since Java 18) deduplicates backing arrays at GC time with no code change, and the JFR “String Deduplication” events show the savings. == comparisons that pass locally and fail against database values are the classic pooling misunderstanding.
Interning everything is a mistake: the pool entries cost lookups and the strings live as long as they are referenced anywhere.
equals defines logical equality between two objects; hashCode returns an int that hash-based collections use to find a bucket. The contract joining them: if a.equals(b) is true, a.hashCode() == b.hashCode() must also be true. Unequal objects may share a hash (a collision), but equal objects may never differ in hash. equals must also be reflexive, symmetric, transitive and consistent, and x.equals(null) must be false.
Breaking the contract breaks HashMap, HashSet and ConcurrentHashMap: a key stored under one hash is looked up under another and silently “disappears”. Overriding only equals is the usual way this happens.
public final class Money {
private final String currency;
private final long cents;
// constructor omitted
@Override public boolean equals(Object o) {
return o instanceof Money m
&& cents == m.cents && currency.equals(m.currency);
}
@Override public int hashCode() {
return Objects.hash(currency, cents);
}
}Records (Java 16+) generate both methods from the components, which removes most of this boilerplate. Use the same fields in both methods, prefer immutable fields (a key whose hash changes while inside a HashSet is lost), and avoid getClass() checks when subclasses should compare equal, or instanceof when they should not.
Apply. Value objects (OrderId, Money, composite cache keys) become records so the methods are generated and consistent. For JPA entities I deliberately do not use generated ids in equals, because the id is null before persist and the entity would change hash while sitting in a Set; I use a natural business key or a client-assigned UUID. Where a class is mutable, it is not used as a map key at all. IDE-generated or Lombok @EqualsAndHashCode is acceptable only when the field list is reviewed.
Test. Every hand-written pair gets an EqualsVerifier test (EqualsVerifier.forClass(Money.class).verify()), which checks symmetry, transitivity, null handling, consistency with hashCode and the final field requirement in one line. A property-based test with jqwik generating random pairs catches asymmetric instanceof comparisons across a class hierarchy.
Troubleshoot. Symptoms are a HashSet that contains returns false for an element you just added, duplicate rows in a de-duplicated collection, or a cache that never hits. The diagnosis is a quick jshell session: compute hashCode() for two objects that equals says are equal. If they differ, one method was overridden without the other or uses a mutable field. Hibernate’s “a different object with the same identifier” error traces back to the same root.
An equals that depends on a lazily loaded JPA association can trigger a database query inside a HashMap.get; keep equality local to the object’s own state.
Overloading is several methods in the same class with the same name and different parameter lists, resolved by the compiler at compile time. Overriding is a subclass replacing an inherited method with the same signature, resolved by the JVM at run time based on the object’s actual class (dynamic dispatch).
| Aspect | Overloading | Overriding |
|---|---|---|
| Resolved | Compile time, from static argument types | Run time, from the object’s class |
| Signature | Same name, different parameters | Identical name and parameters |
| Return type | Free to differ | Same or covariant subtype |
| Access / exceptions | Unconstrained | Not more restrictive; no new checked exceptions |
static methods | Can be overloaded | Hidden, not overridden |
class Shape { double area() { return 0; } }
class Circle extends Shape {
double r = 1;
@Override double area() { return Math.PI * r * r; } // overriding
}
class Printer {
void print(Shape s) { System.out.println("shape"); }
void print(Circle c) { System.out.println("circle"); } // overloading
}
Shape s = new Circle();
new Printer().print(s); // prints "shape": overload chosen by static type
System.out.println(s.area() > 3); // true: override chosen by runtime typeAlways annotate overrides with @Override so a typo in the signature becomes a compile error instead of an accidental overload. Overload resolution with boxing, varargs and null arguments is a frequent source of ambiguity errors.
Apply. Overriding is how a payment service plugs in behaviour: a PaymentGateway abstract class or interface with StripeGateway and AdyenGateway overriding charge, chosen at runtime via dependency injection. Overloading I use sparingly for genuine convenience (of(int), of(String)) and never with parameter types that box or widen into each other (print(long) versus print(Integer)), because callers cannot predict which one they get. For a double-dispatch need (behaviour depending on two runtime types) I reach for a sealed interface with pattern-matching switch (Java 21) instead of overloading, which only sees static types.
Test. Tests for overridden behaviour go through the supertype reference (PaymentGateway g = new StripeGateway()), so they prove dispatch works, and Mockito spy verifies a super.charge() call when a subclass is expected to extend rather than replace. For overloads I add a test per overload with an explicit null argument, since null resolves to the most specific reference overload and that choice should be intentional.
Troubleshoot. “Reference to method is ambiguous” at compile time means two overloads are equally specific; cast the argument or rename one. A subclass method silently never called is a signature mismatch (a missing @Override would have caught it) or a private / static method, which cannot be overridden. Unexpected behaviour when a subclass instance is passed into an overloaded API is the compile-time resolution shown in Q9; the fix is a switch on the runtime type or a virtual method on the object itself.
Overloads differing only in generic type (f(List<String>) versus f(List<Integer>)) do not compile because of erasure.
An abstract class is a partially implemented class that cannot be instantiated; it may hold state, constructors, and a mix of concrete and abstract methods, and a subclass extends exactly one. An interface is a contract of methods a class promises to implement; a class may implement many. Since Java 8 interfaces can carry default and static methods with bodies, and since Java 9 private helper methods, so the old “interfaces have no code” rule no longer holds.
| Aspect | Abstract class | Interface |
|---|---|---|
| Inheritance | Single (extends) | Multiple (implements) |
| State | Instance fields, constructors | Only public static final constants |
| Method bodies | Any | default, static, private only |
| Access control | Any modifier | Members implicitly public |
| Best for | Shared implementation and state | Capability or role across unrelated types |
public interface Notifier {
void send(String to, String body);
default void sendAll(List<String> tos, String body) {
tos.forEach(t -> send(t, body)); // reusable, overridable
}
}
public abstract class RetryingNotifier implements Notifier {
protected final int maxAttempts;
protected RetryingNotifier(int maxAttempts) { this.maxAttempts = maxAttempts; }
protected abstract void doSend(String to, String body);
@Override public void send(String to, String body) { /* retry loop */ }
}Choose an interface for the public type and an abstract class, if needed, as an internal skeleton behind it (the AbstractList pattern). Sealed interfaces (Java 17) add the ability to close the set of implementations.
Apply. Public boundaries are interfaces: OrderRepository, PriceCalculator, Clock. That keeps Spring wiring, mocking and future implementations cheap. Where several implementations share a lifecycle (open connection, do work, record metrics, close) I add a package-private abstract base implementing the template method, so the shared code lives once and subclasses only fill in doWork. A default method is how I add a method to a widely implemented interface without breaking downstream modules; an abstract class would have forced a recompile of every subclass anyway, but the interface change would otherwise be a source-incompatible break.
Test. Each interface gets a contract test: an abstract JUnit 5 test class with the behavioural assertions and a protected abstract T create() hook, which JdbcOrderRepositoryTest and InMemoryOrderRepositoryTest both extend. That proves every implementation honours the same semantics. Abstract classes are tested through a minimal anonymous subclass or Mockito’s CALLS_REAL_METHODS.
Troubleshoot. The “class inherits unrelated defaults” compile error appears when two interfaces supply the same default method; the class must override and pick A.super.m(). A NoSuchMethodError at runtime after adding an interface method means a plugin jar was compiled against the old interface, which is exactly where a default body would have saved the deployment. An AbstractMethodError is the same problem for abstract classes.
Deep abstract-class hierarchies grow brittle; composition plus a small interface usually ages better than a three-level Base* chain.
Inheritance lets a class acquire the fields and methods of a superclass with extends (single inheritance for classes, multiple for interfaces). Polymorphism lets code written against a supertype work with any subtype: a List<Shape> can hold Circle and Square, and calling shape.area() dispatches to the method of the actual runtime class through the JVM’s virtual method table (invokevirtual, or invokeinterface for interfaces).
Java 21 pattern matching adds a second flavour: instead of a virtual method, a switch over a sealed hierarchy branches on the runtime type and the compiler checks exhaustiveness.
This diagram shows a small hierarchy and where dispatch lands.

sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double s) implements Shape {}
static double area(Shape s) {
return switch (s) { // exhaustive: no default needed
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.s() * q.s();
};
}Fields and static methods are not polymorphic; only instance methods dispatch. Prefer composition for code reuse and inheritance for genuine “is-a” relationships, because a subclass is coupled to every implementation detail of its parent.
Apply. In an order-processing service the domain events form a sealed hierarchy (OrderPlaced, OrderPaid, OrderCancelled as records implementing OrderEvent), and consumers use pattern-matching switch so the compiler fails the build when a new event type is added and a handler forgets it. Behavioural variation that belongs to the object (how a DiscountRule computes its reduction) stays a virtual method; variation that belongs to the consumer (how the reporting module renders each event) stays a switch. Class inheritance is limited to one level and base classes are either abstract or final, following the “design for inheritance or prohibit it” rule.
Test. Polymorphic code is tested through the supertype with a parameterised JUnit test fed every implementation (@MethodSource("allRules")), so each subtype runs the same contract. Exhaustiveness is tested by compilation itself; a sealed hierarchy with a missing case does not build.
Troubleshoot. The classic bug is a subclass constructor calling an overridable method before its own fields are initialised, giving a NullPointerException from a half-built object; the fix is to make the method final or move the call. A “fragile base class” regression, where a change to a parent breaks a subclass that relied on call order, is found by the subclass’s own tests and fixed by composition. Unexpectedly slow dispatch at a megamorphic call site (many receiver types at one line) shows up in a JFR profile and can be addressed by splitting the site.
Overusing inheritance for reuse rather than substitutability is the most common long-term maintenance cost in Java codebases.
Generics let classes and methods be parameterised by type (List<String>, <T extends Comparable<T>> T max(...)) so the compiler checks element types and callers avoid casts. Type erasure is how they are implemented: after compilation the type parameters are replaced by their bound (Object or the declared upper bound), and the compiler inserts casts at use sites. The JVM sees one List class, not one per element type, which kept Java 5 binary-compatible with existing libraries.
Erasure explains most generic limitations:
new T(), new T[], instanceof List<String> and T.class are illegal: the type is gone at runtime.List<String> and List<Integer> have the same Class, so you cannot overload on them.List<int> does not exist.getGenericSuperclass), which is how Jackson’s TypeReference<List<Order>> works.List<String> names = new ArrayList<>();
List<Integer> ids = new ArrayList<>();
System.out.println(names.getClass() == ids.getClass()); // true
static <T extends Comparable<T>> T max(List<T> xs) {
T best = xs.get(0);
for (T x : xs) if (x.compareTo(best) > 0) best = x;
return best; // compiles to Comparable, cast at caller
}Wildcards (? extends T for producers, ? super T for consumers, the PECS rule) exist because List<Dog> is not a List<Animal>; generics are invariant.
Apply. Generics give me typed repository and result abstractions: Repository<T, ID>, Result<T, E>, Page<T>, and typed event buses Handler<E extends DomainEvent>. Public API signatures follow PECS (addAll(Collection<? extends T>), Comparator<? super T>). Where a type must survive erasure, I pass a Class<T> token or a super-type token (new TypeReference<List<Order>>() {}) into deserialisers and caches, and I keep a Map<Class<?>, Handler<?>> registry typesafe behind a method that casts once in a controlled place (the typesafe heterogeneous container pattern).
Test. Compile-time behaviour is tested with compile-testing or by keeping deliberately non-compiling snippets in documentation, not tests. Runtime tests cover the erasure edges: deserialising JSON into List<Order> via a TypeReference yields Order elements, not LinkedHashMap, and a generic method handles null and empty lists. Heap-pollution cases get a test that provokes the ClassCastException early.
Troubleshoot. A ClassCastException far from any cast (LinkedHashMap cannot be cast to Order) is a deserialiser that lost the element type; supply a TypeReference or JavaType. “Unchecked” warnings suppressed with @SuppressWarnings deserve a review, since they are exactly where pollution enters. “Name clash: methods have the same erasure” means two overloads differ only in type arguments. For varargs of generic type, @SafeVarargs is only safe when the array never escapes.
Reflection-driven frameworks (Spring, Jackson) see generic signatures in field and method declarations, but never in local variables, which is why List<Order> orders = mapper.readValue(json, List.class) cannot work.
The Collections Framework provides interfaces for grouping objects and standard implementations of each. List is an ordered sequence allowing duplicates and index access; Set holds unique elements; Map holds key-value pairs with unique keys (and is not a Collection itself). Java 21 added SequencedCollection / SequencedMap to give List, LinkedHashSet, LinkedHashMap, TreeSet and friends uniform getFirst, getLast and reversed methods.
| Interface | Main implementations | Ordering | Typical use |
|---|---|---|---|
List | ArrayList, LinkedList, List.of | Insertion / index | Sequences, results, batches |
Set | HashSet, LinkedHashSet, TreeSet, EnumSet | None / insertion / sorted | Uniqueness, membership checks |
Map | HashMap, LinkedHashMap, TreeMap, EnumMap | None / insertion / sorted by key | Lookup tables, caches, indexes |
Queue / Deque | ArrayDeque, PriorityQueue | FIFO / priority | Work queues, BFS, scheduling |
List<String> tags = new ArrayList<>(List.of("b", "a", "b")); // [b, a, b]
Set<String> unique = new TreeSet<>(tags); // [a, b]
Map<String, Integer> counts = new HashMap<>();
for (String t : tags) counts.merge(t, 1, Integer::sum); // {a=1, b=2}
List<String> fixed = List.of("x", "y"); // immutable: add() throwsList.of, Set.of, Map.of and Collectors.toUnmodifiableList (Java 9/10) create immutable collections that reject null. Arrays.asList is fixed-size but write-through to the array. Hash-based implementations depend on correct equals / hashCode; tree-based ones on Comparable or a Comparator consistent with equals.
Apply. Public method signatures declare interfaces (List<Order>), return immutable snapshots (List.copyOf, Collections.unmodifiableMap) and never expose internal mutable collections. Choice of implementation follows access pattern: EnumMap / EnumSet for enum keys, LinkedHashMap where response ordering must be stable for API consumers, TreeMap for range queries on time-series keys, ArrayDeque for stacks and queues (never Stack or LinkedList). Collections sized up front (new ArrayList<>(expected), HashMap.newHashMap(n) in Java 19+) avoid rehash churn when loading large batches.
Test. Collection-returning methods are asserted with AssertJ’s containsExactly (order matters) or containsExactlyInAnyOrder (it does not), which documents the ordering contract. Tests check that returned collections are unmodifiable by expecting UnsupportedOperationException, and that null elements are either rejected or handled, since List.of and Map.of throw on null.
Troubleshoot. ConcurrentModificationException during a for-each loop that removes elements is fixed with removeIf or an explicit Iterator.remove; the same exception across threads points to a shared HashMap that should be a ConcurrentHashMap. Non-deterministic JSON field order in an API response comes from a HashMap where a LinkedHashMap was assumed. A TreeSet “losing” elements has a Comparator inconsistent with equals. A heap dump full of HashMap$Node arrays with low fill ratio indicates oversized initial capacities.
Collections.synchronizedMap protects individual calls, not compound check-then-act sequences; use computeIfAbsent on a ConcurrentHashMap instead.
HashMap stores entries in an array of buckets (default capacity 16, always a power of two). On put, it calls key.hashCode(), spreads the high bits into the low bits (h ^ (h >>> 16)) to compensate for poor hash functions, and selects the bucket with (n - 1) & hash. When size exceeds capacity * loadFactor (0.75), the table doubles and entries are redistributed, which is why many inserts cost amortised O(1) with occasional O(n) resizes.
A collision is two keys landing in the same bucket. Entries in a bucket form a singly linked list; get walks the list comparing stored hash first, then equals. Since Java 8, when a bucket holds more than 8 entries and the table has at least 64 buckets, the list is converted to a red-black tree keyed on hash (and compareTo when keys are Comparable), turning the worst case from O(n) to O(log n) and blunting hash-flooding attacks. The tree reverts to a list when it shrinks to 6.
This diagram shows the table, a chained bucket and a treeified one.
![Diagram: key.hashCode() spread, & (n-1), Node[] table 16 buckets, bucket 3, bucket 9, Node k1, TreeNode > 8 entries, Node k2 (collision)](/interview-questions/java/q19.webp?dpl=dpl_AARaj61vPKcaK1jG3HzJLeoDJPmm)
Iteration order is unspecified and changes on resize. null is allowed as one key and as values. Mutating a key after insertion changes its hash and strands the entry.
Apply. For a product-catalogue cache keyed by SKU I presize with HashMap.newHashMap(expectedSize) (Java 19+) so the load factor is respected without resizes during warm-up, keep keys as immutable records so hashes never drift, and make keys Comparable where a hash-flooding attack is plausible (user-supplied strings) so treeified buckets order by compareTo rather than falling back to identity. Composite keys get a record rather than a concatenated string, which avoids both allocation and accidental collisions like "a|bc" versus "ab|c".
Test. Unit tests feed a map thousands of keys with a deliberately constant hashCode to prove correctness under maximum collision (everything in one bucket) and to measure that lookups remain acceptable thanks to treeification. A JMH benchmark compares the real key distribution with and without presizing, and an EqualsVerifier test guards the key class.
Troubleshoot. Slow get calls under load with HashMap.getNode dominating a JFR profile mean poor hash distribution; print a histogram of hashCode() & (n-1) over real keys to confirm, then fix hashCode (include all fields, use Objects.hash or a 31-multiplier). Entries that vanish are mutated keys. An infinite loop with 100% CPU in HashMap.put / resize is the signature of unsynchronised concurrent writes (less catastrophic since Java 8 but still corrupting); replace with ConcurrentHashMap. Memory bloat from a map sized far above its content shows as a large Node[] in a heap dump.
Relying on HashMap iteration order anywhere is a latent bug waiting for the next resize or JDK upgrade.
ConcurrentHashMap is a thread-safe hash map that allows fully concurrent reads and a high degree of concurrent writes without locking the whole table. Since Java 8 it uses a single Node[] table like HashMap, with reads performed lock-free through volatile reads and writes synchronised per bucket: an empty bucket is filled with a CAS, a populated bucket is locked on its first node only.
Resizing is cooperative, with multiple threads transferring bins in parallel. Buckets treeify under heavy collision, as in HashMap.
Key behaviours:
ConcurrentModificationException and reflect some, not necessarily all, concurrent updates.null keys and values are forbidden, because get returning null must unambiguously mean “absent”.putIfAbsent, computeIfAbsent, compute, merge. The function passed to computeIfAbsent runs under the bin lock, so it must be short and must not touch the same map.size() and mappingCount() are estimates under concurrent modification; aggregate counters use striped CounterCells to avoid contention.forEach, reduce, search) accept a parallelism threshold.ConcurrentHashMap<String, LongAdder> hits = new ConcurrentHashMap<>();
void record(String path) {
hits.computeIfAbsent(path, p -> new LongAdder()).increment();
}Compared with Collections.synchronizedMap, which serialises every call on one monitor, ConcurrentHashMap scales with cores and offers atomic update methods; compared with Hashtable it is the modern replacement in every respect.
Apply. In a rate limiter shared by hundreds of request threads (platform or virtual), ConcurrentHashMap<ClientId, Bucket> with computeIfAbsent gives one atomic “find or create” per client without external locking. Per-key metrics use LongAdder values rather than AtomicLong to spread contention. For a cache with eviction I do not build on ConcurrentHashMap directly; Caffeine does the sizing, expiry and loading correctly and is itself built on it. ConcurrentHashMap.newKeySet() serves as a concurrent set.
Test. Concurrency tests run N threads through a CountDownLatch start barrier hammering merge on a small key set, then assert the final counts equal N times iterations; JCStress is used for the rare case where a custom compound operation needs proof of atomicity. A unit test asserts that computeIfAbsent executes its mapping function exactly once per key under contention (count invocations with an AtomicInteger).
Troubleshoot. A deadlock or IllegalStateException: Recursive update occurs when the function inside computeIfAbsent modifies the same map; restructure so the function is pure. Long bin-lock hold times appear when the mapping function performs I/O (loading from a database): move loading outside or use Caffeine’s async loader. Lost updates almost always trace to a check-then-act written as if (!map.containsKey(k)) map.put(k, v) instead of putIfAbsent. A memory leak is a map used as an unbounded cache; add eviction or a weak-key design.
Thread safety of the map does not make the values thread-safe; a mutable List stored as a value still needs its own synchronisation.
ArrayList stores elements in a resizable array; LinkedList stores them as doubly linked nodes and also implements Deque. The textbook distinction is O(1) random access for ArrayList versus O(1) insertion and removal at the ends for LinkedList, but on modern hardware ArrayList wins almost every practical workload because contiguous memory is cache-friendly and each LinkedList node costs an extra object with two pointers.
| Aspect | ArrayList | LinkedList |
|---|---|---|
get(i) | O(1) | O(n), walks from nearest end |
| Append | Amortised O(1), occasional copy | O(1), allocates a node |
| Insert/remove in middle | O(n) shift, but a fast arraycopy | O(n) to find, O(1) to relink |
| Memory per element | One reference (plus spare capacity) | Node object: element + 2 pointers + header |
| Iterator removal | O(n) | O(1) |
List<Integer> a = new ArrayList<>();
List<Integer> l = new LinkedList<>();
for (int i = 0; i < 1_000_000; i++) { a.add(i); l.add(i); }
// a.get(500_000) is a single array read;
// l.get(500_000) walks 500,000 nodes.When a queue or deque is needed, ArrayDeque beats LinkedList too. The realistic case for LinkedList is frequent removal via a ListIterator while traversing a large list, and even then it is worth measuring.
Apply. ArrayList is the default list everywhere: result sets, batches sent to a Kafka producer, DTO collections. For a batching worker that drains events in FIFO order I use ArrayDeque, and for a sliding window over the most recent N measurements I use a ring buffer over an array. A LinkedList appears only when I need ListIterator.remove / add during a long traversal or need both List and Deque from one object, and a comment explains why. When the size is known (parsing a file with a header count) I pass it to the ArrayList constructor to skip grow-and-copy cycles.
Test. Functional tests do not care which implementation is used, so they are written against List. Performance choices are backed by a JMH benchmark on the real access pattern (append, iterate, remove-while-iterating) with realistic sizes, because intuition about these two classes is frequently wrong. List.of and ArrayList behave differently on null and mutation, so tests assert the expected behaviour explicitly.
Troubleshoot. A loop calling list.get(i) on a LinkedList is quadratic and shows up as LinkedList.node dominating a profile; switching to an iterator or ArrayList fixes it. Excessive GC from millions of LinkedList$Node objects in an allocation profile is another switch-to- ArrayList signal. ArrayList.remove(int) versus remove(Object) confusion with List<Integer> deletes the wrong element; use remove(Integer.valueOf(x)). IndexOutOfBoundsException during removal in a forward loop is the classic shift-after-remove bug; iterate backwards or use removeIf.
Memory headroom matters: an ArrayList can hold up to 50% unused capacity after growth, and trimToSize reclaims it for long-lived lists.
Checked exceptions extend Exception (but not RuntimeException) and the compiler forces callers either to catch them or declare them with throws. Unchecked exceptions extend RuntimeException (or Error) and propagate without declaration. The language intent: checked for recoverable conditions the caller can reasonably handle (IOException, SQLException), unchecked for programming errors (NullPointerException, IllegalArgumentException, IndexOutOfBoundsException). Error subclasses (OutOfMemoryError, StackOverflowError) signal JVM-level failures no application should catch routinely.
| Aspect | Checked | Unchecked |
|---|---|---|
| Base class | Exception | RuntimeException, Error |
| Compiler | Must catch or declare | No obligation |
| Intent | Expected, recoverable failures | Bugs and unrecoverable states |
| Lambdas / streams | Painful: functional interfaces do not declare them | Flow through freely |
| Modern library practice | Rare (Spring wraps JDBC in DataAccessException) | Dominant |
Path p = Path.of("config.yaml");
try {
String text = Files.readString(p); // checked IOException
int port = Integer.parseInt(text.trim()); // unchecked NumberFormatException
} catch (IOException e) {
throw new UncheckedIOException("cannot read " + p, e); // wrap, keep cause
}Most modern Java code favours unchecked exceptions with a small, documented hierarchy, converting checked ones at the boundary and always preserving the cause. Catching Exception or Throwable broadly, or swallowing exceptions silently, is the pattern interviewers most want to hear you reject.
Apply. In a payments service the domain throws a small unchecked hierarchy (PaymentException with InsufficientFunds, GatewayUnavailable), mapped to HTTP status codes in one @ControllerAdvice handler. Checked exceptions from JDBC, I/O and HTTP clients are converted at the adapter layer, wrapping with the original as cause so stack traces remain complete. Where retries make sense I distinguish transient (GatewayUnavailable) from permanent failures with marker types rather than string matching. Inside streams I use a small Unchecked.function(...) wrapper or restructure to a loop so a checked exception does not force an ugly try-catch inside a lambda.
Test. Tests use assertThatThrownBy(...).isInstanceOf(InsufficientFunds.class).hasMessageContaining(...) and verify the cause chain with hasCauseInstanceOf. Negative tests confirm that transient failures trigger exactly the configured retry count (with a fake clock) and that permanent ones do not. The HTTP layer is tested with MockMvc asserting the status code and error body per exception type.
Troubleshoot. A stack trace ending in “Caused by: …” with the root cut off means someone rethrew without the cause; grep for new .*Exception(.*getMessage()). Silent failures trace to empty catch blocks or catch (Exception e) { log.debug }; a static-analysis rule bans both. An UndeclaredThrowableException from a dynamic proxy or ExecutionException from a Future wraps the real failure one level down, so unwrapping in the logging layer is worth doing. Using exceptions for control flow shows as fillInStackTrace in a CPU profile; return a result type instead.
The one place I still like checked exceptions is a library API where every caller must make a decision, such as a ParseException on user input.
try-with-resources (Java 7) declares one or more AutoCloseable resources in the try header and guarantees their close() is called when the block exits, normally or by exception, in reverse declaration order. It replaces the error-prone finally { if (x != null) x.close(); } idiom and solves the problem of a close() exception hiding the original one: the original exception is thrown and any exception from close() is attached to it as a suppressed exception, retrievable with getSuppressed().
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"SELECT total FROM orders WHERE id = ?")) {
ps.setLong(1, orderId);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getBigDecimal(1) : null;
}
} // rs, then ps, then con are closed, even if executeQuery throwsJava 9 allowed an effectively final variable declared earlier to be used in the header (try (existingStream)), avoiding a redundant new variable. Any class can participate by implementing AutoCloseable, which is how you make locks, timers, MDC log contexts and test fixtures scope-safe. ExecutorService became AutoCloseable in Java 19 (its close waits for tasks), and Java 21’s StructuredTaskScope relies on the same mechanism.
The construct is purely compile-time sugar: javac expands it into nested try/finally with the suppression logic, so there is no runtime cost beyond the close() calls themselves.
Apply. Every JDBC, file, socket, HTTP response body, Stream from Files.lines, and Kafka consumer in the codebase is opened in a try header; a code review rule rejects a close() call written by hand. I also wrap custom scoped behaviour in AutoCloseable: an MdcScope that puts a request id into the logging context and removes it on close, a Timer.Sample from Micrometer, and a LockGuard whose close calls unlock. With Java 21 virtual threads, a per-request ExecutorService opened in a try header guarantees child tasks finish before the handler returns.
Test. Unit tests use a fake resource that records close() calls and assert it was closed exactly once, both on the success path and when the body throws. For the exception path I assert the thrown exception is the original and that getSuppressed() carries the close failure. Integration tests check connection-pool metrics (HikariCP active connections) return to zero after a batch of requests, which proves nothing leaks.
Troubleshoot. A HikariCP “Connection is not available, request timed out” after hours of uptime is a leaked connection, usually a ResultSet or Connection obtained outside a try header; Hikari’s leakDetectionThreshold logs the stack trace of the acquisition site. “Too many open files” from the OS is the same bug with file handles, found with lsof -p <pid>. A Stream from Files.lines or Files.list left open is a quiet variant. Resources declared in the header that fail during construction are not closed (they never existed), so a constructor that acquires something must clean up on failure itself.
Order matters: declare the outer resource first so that dependent resources close before the thing they depend on.
A Thread is an OS-backed (platform) or JVM-scheduled (virtual, Java 21) unit of execution. Runnable is the functional interface for a task with no result and no checked exception (void run()); Callable<V> returns a value and may throw (V call() throws Exception). Modern code does not create raw threads per task; it submits Runnable or Callable instances to an ExecutorService, which returns a Future<V> for Callable results.
| Aspect | Runnable | Callable |
|---|---|---|
| Return value | None | V |
| Checked exceptions | Not allowed | Allowed, surfaced via Future.get as ExecutionException |
| Used with | Thread, execute, submit | submit, invokeAll, invokeAny |
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Integer> f = pool.submit(() -> fetchPrice("SKU-1")); // Callable
pool.execute(() -> log.info("audit")); // Runnable
int price = f.get(2, TimeUnit.SECONDS); // blocks
}Virtual threads (JEP 444, final in Java 21) are cheap threads scheduled by the JVM onto a small pool of carrier threads; a blocking call parks the virtual thread instead of the OS thread, so one million blocked virtual threads cost megabytes rather than gigabytes. They suit I/O-heavy request handling. Pooling them is pointless; create one per task. Platform threads remain the choice for CPU-bound work, where parallelism is bounded by cores anyway.
This diagram shows the thread states reported in thread dumps and what moves a thread between them.

Apply. In a Java 21 web service, request handling runs on virtual threads (Spring Boot 3.2+ spring.threads.virtual.enabled=true), and fan-out to three downstream APIs uses StructuredTaskScope (preview through Java 25) or invokeAll on a virtual-thread executor so the subtasks are joined or cancelled together. CPU-heavy work (PDF rendering, compression) goes to a fixed platform pool sized to availableProcessors(). Every pool gets a named ThreadFactory so dumps are readable, and ExecutorService instances are closed in a try header or on application shutdown.
Test. Unit tests inject the executor, and for determinism I substitute a same-thread executor (Runnable::run) so assertions do not race. Behaviour under concurrency is tested with Awaitility (await().atMost(...).untilAsserted(...)) rather than Thread.sleep. For virtual-thread pinning I run the suite with -Djdk.tracePinnedThreads=full (Java 21–23) or watch the jdk.VirtualThreadPinned JFR event.
Troubleshoot. A hung service is diagnosed with jcmd <pid> Thread.print (or jcmd <pid> Thread.dump_to_file -format=json, which includes virtual threads); two threads each BLOCKED on the other’s monitor is a deadlock, many WAITING on a pool queue is starvation. In Java 21, synchronized blocks that perform I/O pin the carrier and can exhaust the carrier pool; the fix is ReentrantLock or upgrading to Java 24+ where JEP 491 removes the pinning. A Callable whose exception vanished was submitted with execute or its Future was never get() -ed; always consume futures or use an UncaughtExceptionHandler.
ThreadLocal on a million virtual threads multiplies memory; prefer ScopedValue (final in Java 25).
synchronized provides mutual exclusion plus visibility: only one thread holds an object’s monitor at a time, and the Java Memory Model guarantees that everything written before a monitor release is visible to a thread that subsequently acquires the same monitor. volatile provides visibility and ordering without exclusion: a write to a volatile field is immediately visible to subsequent reads by any thread, and the compiler and CPU may not reorder accesses across it. It does not make compound operations such as count++ atomic.
| Aspect | synchronized | volatile |
|---|---|---|
| Atomicity | Whole block | Single read or write only |
| Visibility | Yes, via happens-before on the monitor | Yes |
| Blocking | Threads wait for the lock | Never blocks |
| Typical use | Compound state changes | Flags, published configuration references |
class Worker implements Runnable {
private volatile boolean running = true; // visible to the loop thread
private int processed; // guarded by this
public void stop() { running = false; }
public void run() {
while (running) {
synchronized (this) { processed++; } // atomic increment
}
}
}Without volatile, the JIT may hoist running into a register and the loop never ends. The double-checked locking idiom is correct only with a volatile instance field. java.util.concurrent.atomic and VarHandle offer finer-grained memory modes (acquire/release, opaque) when volatile is too strong.
Apply. In a configuration-refresh component, the current config is an immutable object held in a volatile field; the refresher swaps the reference and readers see a consistent snapshot without locking. State that changes in several fields together (a connection pool’s counters) is protected by one lock, documented with @GuardedBy. I keep synchronized blocks short and never call out to I/O or user callbacks while holding a monitor. On Java 21 with virtual threads I use ReentrantLock for anything that blocks inside the critical section, because synchronized pins the carrier thread until Java 24.
Test. Memory-model bugs rarely show in unit tests, so for the few hand-written lock-free pieces I write a JCStress test that runs millions of interleavings and reports forbidden outcomes. Ordinary tests use many threads with a latch and assert invariants (final count equals total increments). Static analysis (Error Prone GuardedBy, SpotBugs IS2_INCONSISTENT_SYNC) runs in CI.
Troubleshoot. A loop that never observes a flag change, only when run without a debugger, is a missing volatile. Lost updates on a counter guarded by volatile alone are the non-atomic ++; switch to AtomicLong or LongAdder. A thread dump showing many threads BLOCKED on one monitor identifies a hot lock; JFR’s “Java Monitor Blocked” events quantify it, and the fix is finer-grained locking, a concurrent collection, or immutability. Deadlocks appear in the dump’s “Found one Java-level deadlock” section with both stacks.
Synchronising on a String literal, a boxed Integer, or this of a public object invites lock sharing with unrelated code; use a private final lock object.
java.util.concurrent.locks provides explicit locks that go beyond synchronized: ReentrantLock (try-lock with timeout, interruptible acquisition, fair ordering, multiple Condition queues), ReentrantReadWriteLock (many readers or one writer), and StampedLock (optimistic reads validated by a stamp, not reentrant). A lock must be released in finally, which is the price for the flexibility.
Atomics (AtomicInteger, AtomicLong, AtomicReference, AtomicIntegerArray) implement lock-free updates with a hardware compare-and-swap: read the value, compute, CAS it in, retry if another thread changed it. LongAdder and LongAccumulator stripe the value across cells to remove contention on hot counters, at the cost of a slower sum(). VarHandle (Java 9) exposes the same CAS and fence operations on any field.
private final ReentrantLock lock = new ReentrantLock();
private final AtomicLong accepted = new AtomicLong();
boolean tryReserve(long qty) throws InterruptedException {
if (!lock.tryLock(200, TimeUnit.MILLISECONDS)) return false;
try {
if (stock < qty) return false;
stock -= qty; // compound update under the lock
accepted.incrementAndGet(); // lock-free counter
return true;
} finally {
lock.unlock();
}
}Choose atomics for a single variable updated independently, a lock when several fields must change together or when you need timeouts and conditions, and LongAdder for write-heavy statistics. Under low contention synchronized and ReentrantLock perform similarly; the explicit lock earns its place through features, not speed.
Apply. An in-memory inventory reservation service uses one ReentrantLock per SKU (stored in a ConcurrentHashMap) so reservations for different products never contend, with tryLock and a timeout so a slow caller gets a fast “retry later” instead of hanging. Request counters and byte totals are LongAdders exported to Micrometer. A rarely updated, frequently read routing table sits behind a StampedLock with optimistic reads. Idempotent “first writer wins” logic uses AtomicReference.compareAndSet on an immutable state record, which also makes the state machine transitions explicit.
Test. JCStress covers the CAS loop on the state record for lost updates. For locks, tests run a thread pool through randomised reserve/release sequences and assert stock never goes negative and lock counts return to zero; a timed test asserts tryLock returns false within the budget while another thread holds the lock. Fairness and starvation are checked with a long-running soak test, not unit tests.
Troubleshoot. A lock never released after an exception (unlock outside finally) presents as every subsequent request timing out on tryLock; the thread dump shows the owner thread idle elsewhere. IllegalMonitorStateException is an unlock from a thread that does not hold the lock. CAS retry storms show as high CPU with AtomicLong.getAndAdd in profiles; LongAdder fixes counters, backoff fixes general CAS loops. Lock ordering deadlocks between two SKUs are prevented by acquiring in a canonical order (sorted by id).
StampedLock is not reentrant and has no condition variables, so calling back into locked code under it deadlocks silently.
CompletableFuture<T> (Java 8) is a Future that can be completed explicitly and, more importantly, composed: you attach dependent stages that run when the result arrives rather than blocking on get(). It implements CompletionStage, whose methods form a pipeline: thenApply (transform), thenCompose (flat-map another future), thenCombine (join two), exceptionally / handle (recover), allOf / anyOf (fan-in), orTimeout / completeOnTimeout (Java 9).
CompletableFuture<Price> price =
CompletableFuture.supplyAsync(() -> pricing.get(sku), ioPool);
CompletableFuture<Stock> stock =
CompletableFuture.supplyAsync(() -> inventory.get(sku), ioPool);
CompletableFuture<Offer> offer = price
.thenCombine(stock, Offer::new)
.orTimeout(800, TimeUnit.MILLISECONDS)
.exceptionally(ex -> Offer.unavailable(sku, ex));This diagram shows the fan-out and fan-in shape of that pipeline.

Two rules matter in practice. First, *Async variants without an executor run on the common ForkJoinPool, which is shared JVM-wide and sized to cores minus one; blocking I/O there starves parallel streams and other users, so pass an explicit executor. Second, non-async stages (thenApply) run on whichever thread completes the previous stage, which may be the caller or the worker, so they must be short and non-blocking.
Exceptions are wrapped in CompletionException inside the pipeline and ExecutionException on get(); join() throws the unchecked wrapper. With Java 21 virtual threads, much of this orchestration can be written as plain blocking code on cheap threads, and CompletableFuture is reserved for genuinely event-driven composition.
Apply. A product-page aggregator fans out to pricing, inventory and reviews with supplyAsync on a dedicated bounded executor, joins with allOf, and degrades each optional section independently via exceptionally so a slow reviews service never blanks the price. Timeouts are per call (orTimeout) and the composite result is returned through Spring’s reactive-friendly CompletableFuture controller return type, so no servlet thread blocks. Every future created without a timeout is treated as a defect. MDC and tracing context are propagated by wrapping the executor (Micrometer ContextExecutorService).
Test. Pipelines are tested with futures completed manually (new CompletableFuture<>() then complete / completeExceptionally) to exercise ordering and failure branches deterministically, and with a same-thread executor to avoid races. Timeout branches are tested by never completing the input future and asserting the orTimeout fallback fires. The ForkJoinPool.commonPool is asserted untouched by running tests with -Djava.util.concurrent.ForkJoinPool.common.parallelism=1.
Troubleshoot. Requests hanging under load with ForkJoinPool.commonPool-worker threads all blocked in socket reads is the shared-pool mistake; move I/O to an explicit pool. A pipeline that “never completes” usually has a stage whose supplier threw before the future was wired, or a thenCompose returning a future nobody completes; CompletableFuture.toString() reports “Not completed” and a thread dump shows no worker. Stack traces lacking the call site are normal for async stages, so I log a correlation id in whenComplete. CompletionException wrapping must be unwrapped (ex.getCause()) before matching exception types.
A forgotten join() on a future created with runAsync means its exception is silently dropped; always attach a terminal handler.
A Stream (Java 8) is a lazy, single-use pipeline over a source (collection, array, Files.lines, generator) consisting of intermediate operations (filter, map, flatMap, sorted, distinct, limit) and one terminal operation (collect, reduce, forEach, count, findFirst, anyMatch). Nothing runs until the terminal operation; elements are then pulled through the whole pipeline one at a time, which lets limit and findFirst short-circuit.
Collectors are recipes for the terminal collect step: toList, toSet, toMap, joining, groupingBy, partitioningBy, counting, summingLong, averagingDouble, mapping, teeing (Java 12), with downstream collectors composable inside groupingBy. Java 16 added Stream.toList() (unmodifiable), and Java 24 added Stream.gather with custom Gatherers for intermediate operations such as windowing.
record Order(String customer, String status, long cents) {}
Map<String, Long> revenueByCustomer = orders.stream()
.filter(o -> o.status().equals("PAID"))
.collect(Collectors.groupingBy(Order::customer,
Collectors.summingLong(Order::cents)));
String top = revenueByCustomer.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse("none");This diagram shows how elements are pulled through the lazy pipeline only when the terminal operation runs.

Primitive streams (IntStream, LongStream) avoid boxing and add sum, average, summaryStatistics. parallelStream splits the work across the common ForkJoinPool; it pays off only for large, CPU-bound, easily split sources (arrays, ArrayList) and hurts when the lambda does I/O or when results must be ordered. Streams should be stateless and side-effect-free; mutating shared state inside map or forEach defeats the model.
Apply. Streams replace loops where the pipeline reads as a transformation: mapping entities to DTOs, grouping a day’s orders by status for a dashboard, or Files.lines(path) streamed through filter / map to a BufferedWriter for large CSV transformations without loading the file. Business aggregations use groupingBy with downstream summingLong / mapping, and teeing when two aggregates are needed in one pass. I avoid streams for simple loops with early exits and side effects, and I never use parallelStream inside a request handler, since the common pool is shared across the whole JVM.
Test. Stream pipelines are pure functions, so they get table-driven unit tests with small fixtures covering empty input, duplicates, and null fields (Collectors.toMap throws on null values and on duplicate keys). AssertJ’s containsExactly guards ordering where sorted is used. For a parallel pipeline that is actually justified, a test runs it with ForkJoinPool parallelism of 1 and 8 and asserts identical output.
Troubleshoot. IllegalStateException: stream has already been operated upon or closed is a reused Stream variable; recreate it from the source. IllegalStateException: Duplicate key from toMap needs a merge function. A pipeline that seems to do nothing lacks a terminal operation. Slow parallel code with threads blocked in JDBC calls is I/O on the common pool. Deep stack traces full of ReferencePipeline$3$1.accept are normal and not a performance signal; a JFR allocation profile pointing at boxed Integer in Stream<Integer> is, and mapToInt fixes it.
Streams over large Files.lines sources must be closed with try-with-resources or the file handle leaks.
Optional<T> (Java 8) is a container that either holds a non-null value or is empty, intended as a return type that makes “no result” explicit in the method signature so callers cannot forget to handle it. It replaces the ambiguity of a null return with a type the compiler sees. The fluent API (map, flatMap, filter, orElse, orElseGet, orElseThrow, ifPresentOrElse, or, stream) lets callers transform or default without if (x != null) chains. OptionalInt, OptionalLong and OptionalDouble avoid boxing.
Optional<Customer> findByEmail(String email) { /* repository call */ }
String displayName = findByEmail(email)
.map(Customer::preferredName) // skipped when empty
.filter(n -> !n.isBlank())
.orElse("Guest");
Customer c = findByEmail(email)
.orElseThrow(() -> new CustomerNotFound(email));Rules the JDK authors themselves give: use it only as a return type; do not use it for fields, method parameters, or collection elements (it adds allocation and is not Serializable); do not call get() or isPresent() where map / orElseThrow express the intent; return an empty collection rather than Optional<List<T>>. orElse(expensive()) always evaluates the argument, so orElseGet is right for anything non-trivial.
Null safety beyond Optional: Objects.requireNonNull at constructor boundaries, @Nullable / @NonNull annotations (JSpecify is the emerging standard, checked by NullAway or the Kotlin-style IDE inspections), records with validation in compact constructors, and Java 14+ helpful NullPointerException messages that name the exact null expression. Java 25 does not yet include language-level nullness markers; JEP drafts for String! / String? types remain in progress.
Apply. Repository and lookup methods return Optional<T> (Spring Data does this natively with findById), service code chains map / orElseThrow into a domain exception, and the HTTP layer turns that into a 404 in one place. Internally, nullability is declared with JSpecify annotations and @NullMarked at package level, so every unannotated type is non-null by default and NullAway fails the build when a possibly-null value is dereferenced. Required constructor arguments pass through Objects.requireNonNull in records’ compact constructors; optional ones are modelled as Optional - returning accessors over a nullable field, never as Optional fields serialised by Jackson.
Test. Tests assert Optional results with AssertJ (assertThat(result).isEmpty(), .contains(expected)), which reads better than isPresent() checks. A contract test confirms that every public API method rejects null arguments with NullPointerException and a meaningful message, generated by iterating the methods reflectively or using Guava’s NullPointerTester. Deserialisation tests send JSON with missing and explicit- null fields to confirm the domain object either defaults or rejects as intended.
Troubleshoot. A NoSuchElementException: No value present is an unguarded Optional.get(); replace with orElseThrow(() -> ...) naming the context. An NPE in production is read from its Java 14+ helpful message (“Cannot invoke String.trim() because the return value of getName() is null”), which pinpoints the null expression without a debugger. Performance regressions after introducing Optional in a hot loop show as allocation in JFR; use a nullable local or OptionalInt there. Jackson serialising Optional as {"present":true} means the jackson-datatype-jdk8 module is missing.
Treating Optional as a general null-replacement everywhere makes code noisier without making it safer; the boundary discipline is what prevents NPEs.
Each thread has its own stack of frames holding local variables, primitives, and references, pushed on method entry and popped on return, so stack memory needs no collector and its depth limit produces StackOverflowError. Objects live on the shared heap, allocated by new, and reclaimed by the garbage collector when no live reference reaches them. Class metadata lives in Metaspace (native memory, since Java 8), and JIT code in the code cache.
HotSpot collectors are generational or region-based. Young objects die fast, so new allocations go to Eden through thread-local allocation buffers; survivors are copied to survivor spaces and eventually promoted to the old generation. Collection is tracing from GC roots (thread stacks, static fields, JNI handles), not reference counting, so cycles are collected.
This diagram shows the memory areas and where allocation and promotion flow.

| Collector | Default since | Design goal |
|---|---|---|
| Serial | Small heaps, 1 CPU | Minimal footprint |
| Parallel | Java 8 default | Maximum throughput, long pauses |
| G1 | Java 9 default | Balanced, region-based, pause target |
| ZGC (generational) | Java 23 default mode | Sub-millisecond pauses on huge heaps |
| Shenandoah | Red Hat / OpenJDK option | Concurrent, low pause |
OutOfMemoryError means live data exceeds the heap or Metaspace, not that the collector is slow. | ||
System.gc() is a hint and usually a mistake. |
Apply. Services run in containers with an explicit -Xmx or -XX:MaxRAMPercentage=75 so the JVM respects the cgroup limit and leaves room for Metaspace, thread stacks and off-heap buffers. Latency-sensitive APIs on Java 21+ use generational ZGC (-XX:+UseZGC -XX:+ZGenerational, the only ZGC mode since Java 24); batch jobs keep Parallel GC for throughput; most others stay on G1 with a MaxGCPauseMillis target. Every JVM logs GC (-Xlog:gc*:file=gc.log) and runs with -XX: +HeapDumpOnOutOfMemoryError to a persistent volume. Java 25’s compact object headers (-XX: +UseCompactObjectHeaders) cut per-object overhead and are worth enabling after testing.
Test. Load tests export JVM metrics (Micrometer jvm.gc.pause, jvm.memory.used) and the pass criteria include p99 GC pause and no upward old-generation trend across a 30-minute soak, which is the practical leak test. Allocation hot spots are measured with JFR allocation profiling or async-profiler in alloc mode before and after optimisations.
Troubleshoot. OutOfMemoryError: Java heap space gets a heap dump analysed in Eclipse MAT; the dominator tree names the retaining class (a static cache, an unbounded ConcurrentHashMap, a listener list). Metaspace OOM is class-loader leaks, typical with hot redeploys or runtime proxy generation. A container killed by the OOM-killer while the heap looks fine is native memory: thread stacks, direct ByteBuffers, or the JIT; -XX:NativeMemoryTracking=summary with jcmd VM.native_memory breaks it down. Long pauses in gc.log with “to-space exhausted” (G1) mean the heap is too small for the allocation rate. StackOverflowError is recursion depth; raise -Xss only after confirming the recursion is bounded.
A JVM that uses 90% of a container’s memory is not leaking; it is using the heap you gave it, and only a trend tells you otherwise.
A record (Java 16) is a concise, immutable data carrier: record Point(int x, int y) {} generates a canonical constructor, private final fields, accessors x() and y(), and equals, hashCode and toString based on all components. Records can declare compact constructors for validation, static factories, instance methods and nested types, and can implement interfaces, but cannot extend a class or declare additional instance fields. They are implicitly final.
A sealed class or interface (Java 17) restricts which types may extend it with permits; every permitted subtype must be final, sealed or non-sealed, and must be in the same module (or package, for the unnamed module). The compiler therefore knows the complete set of subtypes, which enables exhaustive pattern-matching switch (Java 21) without a default branch.
sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String authCode, long cents) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Pending(Instant retryAfter) implements PaymentResult {}
String describe(PaymentResult r) {
return switch (r) {
case Approved(var code, var cents) -> "approved " + code + " " + cents;
case Declined d when d.reason().isBlank() -> "declined";
case Declined d -> "declined: " + d.reason();
case Pending p -> "retry at " + p.retryAfter();
};
}Together they model algebraic data types: records are the product types, sealed hierarchies the sum types. Record patterns (Java 21) deconstruct components inline, and when guards refine cases. Adding a new permitted subtype makes every exhaustive switch fail to compile, which is exactly the safety that instanceof chains never provided. Records are not JavaBeans (no getX naming, no setters), so frameworks need Java 16+ support, which Jackson, Spring and Hibernate 6 provide.
Apply. DTOs, API request and response bodies, configuration properties (@ConfigurationProperties on a record in Spring Boot 3), value objects and map keys are all records; compact constructors enforce invariants (if (cents < 0) throw new IllegalArgumentException(...)) and normalise input (trim, upper-case currency). Domain outcomes that used to be a status enum plus nullable fields become a sealed interface of records (Approved, Declined, Pending), so a declined result cannot carry an auth code by construction. Kafka event schemas map to a sealed OrderEvent hierarchy consumed with exhaustive switch.
Test. Records need no equals / hashCode tests, so testing moves to the compact constructor: a parameterised test over invalid inputs asserts the exception and message. Serialisation round-trip tests (Jackson writeValueAsString then readValue) confirm component names map to JSON fields and that polymorphic sealed types carry a discriminator (@JsonTypeInfo or Jackson’s sealed-type support). Exhaustiveness is verified by the compiler; I keep a deliberately failing branch in code review notes when adding a subtype to show where handling was added.
Troubleshoot. A switch that suddenly fails to compile after a dependency upgrade means the library added a permitted subtype; that is the feature working. Jackson throwing “Cannot construct instance … no Creators” on a record means an old Jackson (pre-2.12) or missing -parameters, which is unnecessary from 2.12 onward. IncompatibleClassChangeError at runtime appears when a class compiled against a non-sealed hierarchy tries to extend a now-sealed type. Hibernate cannot map records as entities (no no-arg constructor, no setters), so they stay as embeddables or projections.
Records make shallow immutability only; a List component should be defensively copied with List.copyOf in the compact constructor.
Annotations are structured metadata attached to declarations (classes, methods, fields, parameters, type uses) and, since Java 8, to type uses and repeatable sites. They do nothing by themselves; a processor reads them, either at compile time (annotation processors such as Lombok, MapStruct, Dagger, or javac ’s own checks for @Override, @FunctionalInterface, @Deprecated) or at run time via reflection when declared with @Retention(RUNTIME).
This diagram shows the two paths by which an annotation gets acted on.

Reflection (java.lang.reflect) lets code inspect and manipulate classes at run time: list fields and methods, read annotations, instantiate objects, invoke methods, and set fields, including private ones via setAccessible(true). It is the machinery under dependency injection, JPA, Jackson, JUnit and most Java frameworks.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited { String action(); }
for (Method m : service.getClass().getDeclaredMethods()) {
Audited a = m.getAnnotation(Audited.class);
if (a != null) {
System.out.println(m.getName() + " -> audit: " + a.action());
}
}Costs and limits: reflective calls are slower than direct ones (though the JIT inlines many), they bypass compile-time type checking, and since Java 16 the JDK’s own internals are strongly encapsulated, so setAccessible on java.base classes fails with InaccessibleObjectException unless --add-opens is given. MethodHandle and VarHandle (java.lang.invoke) are the faster, type-checked modern alternative, and GraalVM native image requires reflection to be declared up front because the closed-world compiler cannot discover it.
Apply. Application code uses annotations declaratively and reflection almost never: @Transactional, @Valid with Bean Validation constraints, @Scheduled, and a few custom ones such as @RateLimited(permits = 100) implemented by a Spring AOP aspect that reads the annotation once and caches it per method. Compile-time processing is preferred for code generation (MapStruct mappers, immutables), because errors surface in the build rather than at startup. Where reflection is unavoidable (a plugin loader discovering @Extension classes), lookups happen once at startup, results are cached in a Map<Class<?>, MethodHandle>, and MethodHandle replaces Method.invoke on hot paths.
Test. An ArchUnit test asserts architectural rules the annotations imply: every class annotated @RestController lives in the api package, every @Transactional method is public and on a Spring bean. Aspects are tested through the Spring context (the annotation on a self-invoked private method is silently ignored, a classic trap worth a dedicated test). Annotation processors get compile-testing unit tests that compile a snippet and assert the generated source.
Troubleshoot. An annotation “doing nothing” usually has @Retention(SOURCE) or CLASS instead of RUNTIME, or the proxied method is called from inside the same class so the proxy is bypassed. InaccessibleObjectException: module java.base does not open java.lang after a JDK upgrade is strong encapsulation; the right fix is a library upgrade, the stopgap is --add-opens java.base/java.lang=ALL-UNNAMED. Slow startup with thousands of classes scanned shows in a JFR profile as Class.forName; narrow @ComponentScan. GraalVM native image failing with ClassNotFoundException for a reflectively used class needs a reflect-config.json entry or the tracing agent.
Lombok-style processors that hack javac internals break on new JDKs faster than clean processors; budget for that on each LTS upgrade.
JDBC is the standard Java API for relational databases: a DriverManager or DataSource yields a Connection, from which you create Statement / PreparedStatement, execute SQL, and read ResultSet rows; transactions are controlled with setAutoCommit(false), commit, rollback. Vendor drivers implement the interfaces, so application code is portable apart from SQL dialect. PreparedStatement binds parameters server-side, which prevents SQL injection and lets the database reuse plans.
Opening a physical connection costs a TCP handshake, TLS, authentication and server-side session setup, often tens of milliseconds, and databases cap concurrent connections. A connection pool keeps a fixed set of open connections and hands them out on getConnection(), returning them on close(). HikariCP is the de facto standard (Spring Boot default); it validates connections, enforces maximumPoolSize, connectionTimeout, idleTimeout and maxLifetime, and can detect leaks.
This diagram shows the request path through the pool.

Pool sizing is counter-intuitive: a small pool (roughly cores times two, plus spindle count) usually beats a large one because the database serialises on CPU and disk anyway, and excess connections just queue inside the database instead of inside the application. Higher-level APIs (JPA/Hibernate, jOOQ, Spring JdbcClient) all sit on JDBC and the same pool.
Apply. Spring Boot’s auto-configured HikariCP pool is tuned per service: maximumPoolSize of 10 for a typical API instance, connectionTimeout 3 s so callers fail fast, maxLifetime a minute shorter than the database or proxy idle timeout so connections are recycled before being killed, and leakDetectionThreshold 10 s in non-production. Transactions are kept short and never span remote calls, and read-only reporting queries use a separate pool against a replica. On Java 21 with virtual threads the pool size still bounds concurrency, so a 10-connection pool with 10,000 virtual threads simply queues; that is correct and protects the database.
Test. Repository tests run against the real database engine in Testcontainers, not H2, because SQL dialects and driver behaviour differ. A load test watches Hikari metrics (hikaricp.connections.pending, hikaricp.connections.timeout, acquisition time p99) and the database’s own connection count; sustained pending connections mean the pool is undersized or transactions are too long. A chaos test kills the database mid-run and asserts the pool recovers without restart.
Troubleshoot. SQLTransientConnectionException: request timed out after 3000ms with active == max and low database CPU is a leak or a long transaction; the leak-detection stack trace or pg_stat_activity (state = 'idle in transaction') names the culprit. “Connection reset” bursts at a fixed interval are a firewall or pgbouncer idle timeout shorter than maxLifetime. Slow queries are caught with log_min_duration_statement or driver-level logging (p6spy, datasource-proxy) and fixed with indexes or by removing N+1 selects seen as hundreds of identical statements per request.
The pool makes connections cheap; it does not make transactions cheap, and holding a connection across an HTTP call is the mistake behind most “pool exhausted” incidents.
Profiling measures where a running JVM spends CPU, allocates memory, blocks on locks or waits on I/O; tuning changes JVM flags or code based on that evidence. The core modern tool is JDK Flight Recorder (JFR), built into the JVM since Java 11 with roughly one to two percent overhead, started with -XX:StartFlightRecording or jcmd <pid> JFR.start, and analysed in JDK Mission Control. It records method samples, allocation sites, GC events, lock contention, thread parking, exceptions and, from Java 21, virtual-thread events. async-profiler complements it with accurate native-aware CPU and allocation flame graphs. Everyday diagnostics come from jcmd (thread dumps, heap histograms via GC.class_histogram, native memory tracking), jstat -gcutil for live GC counters, and Micrometer metrics exported to Prometheus for trends.
Tuning follows a hierarchy: fix the code first (algorithms, caching, N+1 queries, excessive allocation), then size the heap for the live set, then choose the collector for the latency or throughput goal, and only then touch exotic flags. Important knobs on Java 17–25: -Xmx / -XX:MaxRAMPercentage, collector selection (-XX:+UseG1GC, -XX:+UseZGC, -XX:+UseParallelGC), -XX:MaxGCPauseMillis for G1, -Xss for thread stacks, -XX:ReservedCodeCacheSize, and Class Data Sharing / AOT cache (-XX:AOTCache, Java 24+ via Project Leyden) for startup. JIT warm-up matters: measure after steady state, and use JMH for microbenchmarks, because naive System.nanoTime loops are defeated by dead-code elimination and constant folding.
Interview takeaway: profile before tuning, change one variable at a time, and prefer JFR evidence over folklore flags copied from old blog posts.
Apply. Production services run continuous JFR with a bounded repository (-XX:StartFlightRecording=disk=true,maxsize=256m,maxage=12h,settings=profile) so a recording of the last incident is always available, and jcmd JFR.dump extracts it on demand. Dashboards track heap after GC, GC pause p99, allocation rate, thread count and CPU per pod. JVM flags are kept in a JAVA_TOOL_OPTIONS environment variable in the deployment manifest, reviewed like code. For startup-critical services (serverless, autoscaled pods) I use Spring AOT plus an AOT cache (Java 24+) or CRaC where supported, and measure time-to-first-request rather than guess.
Test. Every performance change ships with a before/after flame graph and a load test at production-like concurrency; the acceptance criteria are p99 latency, allocation rate and GC pause, not just throughput. JMH benchmarks live in a separate module and run nightly to catch regressions in hot utilities. Canary deployments compare JVM metrics between old and new versions for an hour before full rollout.
Troubleshoot. High CPU with low throughput: a 60-second async-profiler flame graph; if the top frames are GC threads, the heap is undersized or allocation is excessive; if they are String.format, regex compilation or log.debug string building, fix the code. Rising latency with flat CPU: JFR “Java Monitor Blocked” and “Thread Park” events reveal lock contention or pool starvation. Slow startup: -Xlog:class+load counts classes and -Xshare or AOT cache usage is verified. Memory growth: compare two heap histograms (jcmd GC.class_histogram) ten minutes apart before taking a full dump.
The common mistake is copying flags between services with different workloads; a batch job’s Parallel GC settings will wreck an API’s latency.
Add your resume and the job description in CrackItX's Settings. When the interviewer asks a Java question, Claude suggests an answer using your real projects and the role's requirements, in real time.
See pricing →