Java Core Senior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. Why does double-checked locking for a lazy singleton need a volatile field?

    private static Config instance;
    static Config get() {
        if (instance == null) {
            synchronized (Config.class) {
                if (instance == null) instance = new Config();
            }
        }
        return instance;
    }

    Correct answer: Without it, another thread may see the reference before the object is fully built

    The write of the reference can be reordered with the constructor's writes. volatile gives the happens-before edge. A holder class or enum is simpler.

  2. 2. What does 'happens-before' mean in the Java Memory Model?

    Correct answer: If A happens-before B, B is guaranteed to see A's effects

    Unlock-then-lock, volatile write-then-read, thread start and join create such edges. Without one, reads may see stale values.

  3. 3. Why are properly built immutable objects safe to share between threads?

    Correct answer: Final fields are guaranteed visible after construction, and nothing changes

    The final-field semantics guarantee safe publication if this doesn't escape the constructor.

  4. 4. What's wrong with this cache code under concurrency?

    if (!map.containsKey(k)) {
        map.put(k, load(k));
    }
    return map.get(k);

    Correct answer: Check-then-act isn't atomic; use computeIfAbsent

    Two threads can both load. computeIfAbsent runs the function once per key, but keep it short: it blocks other updates for that key.

  5. 5. Which thread runs CompletableFuture.supplyAsync(task) without an executor?

    Correct answer: A thread from the shared ForkJoinPool.commonPool

    Blocking I/O in the common pool starves parallel streams and other async code. Pass a dedicated executor for I/O.

  6. 6. An exception is thrown inside thenApply. What does the caller see on join()?

    Correct answer: A CompletionException wrapping the original cause

    Handle with exceptionally or handle, and unwrap getCause() in tests to assert on the real exception.

  7. 7. When do virtual threads (JEP 444) help most?

    Correct answer: Many concurrent tasks that mostly wait on I/O

    Virtual threads are cheap to block. For CPU-bound work the number of cores is still the limit.

  8. 8. What can 'pin' a virtual thread to its carrier in Java 21?

    Correct answer: Blocking inside synchronized or a native call

    A pinned virtual thread blocks the carrier, hurting throughput. ReentrantLock avoids this; later JDKs reduce pinning from synchronized.

  9. 9. Why are ThreadLocals a concern with millions of virtual threads?

    Correct answer: Each thread gets its own copy, so memory use can explode

    Caching heavy objects per thread was cheap with pools of 200; it's not with a million threads. Scoped values are the newer alternative.

  10. 10. What does structured concurrency (JEP 453) aim to fix?

    Correct answer: Subtasks that outlive the task that started them

    Subtasks are joined in a scope: if one fails, the others are cancelled, and none keep running after the scope ends.

  11. 11. Which garbage collector is the default in modern JDKs on servers?

    Correct answer: G1

    G1 balances throughput and pauses. ZGC and Shenandoah target very low pauses; CMS was removed in JDK 14.

  12. 12. When would you pick ZGC over G1?

    Correct answer: When short pauses matter more than raw throughput, with large heaps

    ZGC keeps pauses around milliseconds even for large heaps, at some CPU cost. Measure with real load.

  13. 13. Why should -Xmx or MaxRAMPercentage be set for a JVM in a container?

    Correct answer: So the heap fits the container limit and the process isn't OOM-killed

    Modern JVMs read container limits, but defaults use a fraction of RAM. Leave room for metaspace, threads and native memory.

  14. 14. Test runs grow slower and finally fail with OutOfMemoryError: Metaspace. What's a common cause?

    Correct answer: Class loaders are leaked, so loaded classes are never freed

    Each test context or plugin may create class loaders. A static reference to one keeps all its classes alive.

  15. 15. What are GC logs useful for when tests or services pause randomly?

    Correct answer: They show pause times, causes and heap use over time

    Enable with -Xlog:gc*. Long or frequent pauses correlate with timeouts and flaky latency.

  16. 16. Why are naive microbenchmarks in Java often wrong?

    Correct answer: JIT warm-up, dead-code removal and GC skew the timing

    JMH handles warm-up, forks and blackholes. A loop timing with System.nanoTime often measures the wrong thing.

  17. 17. In a JMH benchmark, why consume results with a Blackhole or return them?

    Correct answer: So the JIT can't remove the computation as unused

    If the result is unused, the JIT may skip the work, and the benchmark shows impossibly fast times.

  18. 18. What does junit.jupiter.execution.parallel.enabled=true change?

    Correct answer: Lets JUnit run tests concurrently, per class or method

    Tests touching shared resources need @ResourceLock or @Isolated, or they'll interfere.

  19. 19. What does @ResourceLock("DB") do in JUnit 5?

    Correct answer: Stops tests that share that resource from running together

    It keeps parallel runs fast while serializing tests that would clash on a shared resource.

  20. 20. With TestNG parallel="methods", why do tests sharing instance fields break?

    Correct answer: Methods of one instance run at the same time and share its fields

    Keep per-test state local or in ThreadLocal, or use parallel="classes" if a class must stay sequential.

  21. 21. Why use Testcontainers in Java integration tests?

    Correct answer: Real databases and services run in throwaway containers

    Tests run against the real database version, not an in-memory substitute with different SQL behavior.

  22. 22. What's the main risk of over-mocking in Java unit tests?

    Correct answer: Tests mirror the code and break on refactors, yet miss bugs

    Mock at boundaries (network, time, external systems). Use real objects for simple collaborators.

  23. 23. Why should JPA entity equals not rely on a generated id alone?

    Correct answer: New entities have a null id, so their hash changes after save

    An entity in a HashSet gets lost when its id is assigned. Use a business key or a stable id strategy.

  24. 24. Why did many libraries break when moving from Java 8 to 17?

    Correct answer: Strong encapsulation blocks deep reflection into JDK internals

    Illegal reflective access became an error. Upgrade libraries or open specific packages with --add-opens as a last resort.

  25. 25. What is heap pollution with generic varargs?

    static <T> T[] arr(T... items) { return items; }

    Correct answer: A variable of a generic type points to an object of another type

    Generic arrays can't be checked at runtime, so a ClassCastException appears far from the cause. @SafeVarargs documents a safe method.

  26. 26. Why does Collectors.toMap(...) throw IllegalStateException on some data?

    Correct answer: Two elements gave the same key and no merge function was set

    Pass a merge function as the third argument, e.g. (a, b) -> a. Null values also throw NPE in toMap.

  27. 27. Why is logging with log.debug("Order " + order) wasteful?

    Correct answer: The string is built even when debug logging is off

    Use placeholders: log.debug("Order {}", order). The message is formatted only if the level is enabled.

  28. 28. Why does logging context (MDC) disappear in tasks on a thread pool?

    Correct answer: MDC is thread-local, so it must be copied to the worker thread

    Wrap executors or tasks to propagate the context, otherwise trace or request ids vanish in async logs.

  29. 29. What does a sealed interface plus records give for domain modeling?

    sealed interface Payment permits Card, Bank {}
    record Card(String number) implements Payment {}
    record Bank(String iban) implements Payment {}

    Correct answer: A closed set of data types that switch checks exhaustively

    Algebraic data types make invalid states harder to express and force handling new variants.

  30. 30. Why may a switch with patterns fail to compile with 'dominated' cases?

    switch (obj) {
        case CharSequence cs -> ...
        case String s -> ...
    }

    Correct answer: A broader case before a narrower one makes the narrower unreachable

    Put specific cases first. The compiler rejects unreachable patterns to avoid silent bugs.

  31. 31. What's the risk of stream().parallel() on a LinkedList or with blocking calls?

    Correct answer: Poor splitting and blocked pool threads can make it slower

    Parallel speedup needs splittable sources, enough work per element and no blocking. Measure before using it.

  32. 32. Why can autoboxing hurt performance in hot code?

    Map<Integer, Long> counts = new HashMap<>();
    for (int i : ids) counts.merge(i, 1L, Long::sum);

    Correct answer: Each boxed value allocates objects and adds GC pressure

    Primitive collections or arrays avoid the overhead when profiling shows it matters.

  33. 33. What does a thread dump help with in a hanging test run?

    Correct answer: It shows what every thread is doing and which locks it waits on

    Take it with jstack or jcmd Thread.print. Deadlocks are reported directly.

  34. 34. Why should a test framework's driver or client factory be thread-safe?

    Correct answer: Parallel tests create and close instances at the same time

    Lazy init without synchronization can create two drivers or hand one driver to two threads.

  35. 35. What problem does a test data builder solve?

    User user = aUser().withRole(ADMIN).build();

    Correct answer: Tests set only fields that matter, with defaults for the rest

    When the User class gets a new required field, only the builder changes, not hundreds of tests.

  36. 36. Why is catch (InterruptedException e) {} a bug?

    Correct answer: It loses the interrupt, so the thread can't be stopped properly

    Restore the flag with Thread.currentThread().interrupt() or rethrow. Executors rely on interrupts to shut down.

  37. 37. Why does ExecutorService.shutdown() matter in tests?

    Correct answer: Non-daemon threads keep the JVM alive and leak between tests

    Use try-with-resources on executors (Java 19+) or shut down and awaitTermination in @AfterEach.

  38. 38. What happens when you call hashCode on a mutable record used as a map key?

    record Key(List<String> parts) {}

    Correct answer: The hash changes if the list changes, so lookups can fail

    A record is only as immutable as its components. Copy lists into immutable ones in the constructor.

  39. 39. Why prefer composition over inheritance in a large test framework?

    Correct answer: Deep base-test trees get rigid; helpers mix in per test

    A BaseTest that does everything forces every test to pay for setup it doesn't need. Extensions and helpers compose better.

  40. 40. What do JUnit 5 extensions (@ExtendWith) offer over base classes?

    Correct answer: Reusable hooks for setup, injection and reports, no inheritance

    Mockito, Spring and Testcontainers ship extensions. Several can be combined on one class.

  41. 41. Why should exception messages include context in a test framework?

    Correct answer: "Element not found" alone doesn't say which page or locator

    Good messages cut triage time: what was expected, where, with which input.

  42. 42. What's the issue with a static SimpleDateFormat shared by threads?

    Correct answer: It isn't thread-safe and can return wrong dates under load

    Use the immutable, thread-safe DateTimeFormatter from java.time.

  43. 43. How do you make code that reads System.getenv testable?

    Correct answer: Wrap it behind an interface or pass config in, then inject a fake

    Environment and time are global state. Injecting them keeps tests isolated and parallel-safe.

  44. 44. Why can equals that uses instanceof break symmetry with subclasses?

    Correct answer: a.equals(b) may be true while b.equals(a) is false

    Mixing a Point and a ColorPoint is the classic case. Make classes final or use getClass() comparison.

  45. 45. When is ReentrantLock a better choice than synchronized?

    Correct answer: When you need tryLock with timeout, fairness or interruptible locking

    Always unlock in finally. synchronized is simpler when you need none of those features.

  46. 46. Why may a ConcurrentHashMap.computeIfAbsent that calls itself deadlock or fail?

    Correct answer: Recursive updates on the same map inside the function aren't allowed

    Keep the mapping function short and side-effect free; compute dependencies outside first.

  47. 47. What does ExecutorService.invokeAll with a timeout give you?

    Correct answer: Runs tasks and cancels those not done when time runs out

    Check isCancelled on the futures. Good for fan-out calls with an overall deadline.

  48. 48. Why is a flaky test that passes on retry still a problem in Java suites?

    Correct answer: It hides real races and erodes trust in red builds

    Track flaky tests, quarantine them and fix causes: shared state, sleeps, time, order.

  49. 49. What is a common cause of tests that fail only on CI machines with more cores?

    Correct answer: Race conditions that appear only with real parallelism

    Higher parallelism and different timing expose unsynchronized state. Reproduce with stress loops or parallel runs locally.

  50. 50. Why is Thread.stop() gone?

    Correct answer: It killed threads mid-work and left broken objects

    Cooperative cancellation via interrupt lets code clean up and keep invariants.

  51. 51. What does Stream.toList() return compared to collect(Collectors.toList())?

    Correct answer: An unmodifiable list; the collector makes no such promise

    Code that adds to the result after switching to toList() throws UnsupportedOperationException.

  52. 52. Why may a Java service using a JDBC pool hang after a database failover?

    Correct answer: Pooled connections point to the dead node, and calls block

    Set connect, socket and validation timeouts, and configure the pool to test connections.

  53. 53. What's the downside of catching Throwable in a test listener?

    Correct answer: It swallows Errors like OutOfMemoryError and hides crashes

    Catch specific exceptions; let Errors kill the run so the root cause is visible.

  54. 54. Why prefer List.copyOf over Collections.unmodifiableList for API return values?

    Correct answer: copyOf is an independent snapshot; a view shows changes

    Callers can't see later internal changes through a copy. Note that copyOf rejects nulls.

  55. 55. What does jcmd <pid> GC.heap_dump give you?

    Correct answer: A heap snapshot showing which objects use memory

    Open it in a tool like Eclipse MAT; look at dominators and GC roots of the biggest objects.

  56. 56. Why can a Java test pass in the IDE but fail with Maven?

    Correct answer: Different classpath, JVM flags, encoding or test order

    Surefire config, forking and default encoding (before Java 18) often differ. Reproduce with the same command as CI.

  57. 57. Why should library code avoid System.exit?

    Correct answer: It kills the whole JVM, including the test runner

    Throw an exception and let the caller decide. Tests can't recover from an exit.

  58. 58. What's a safe way to publish an object to other threads?

    Correct answer: Through a volatile field, a lock, a concurrent collection or final

    Each of these creates a happens-before edge. Plain fields give no visibility guarantee.

  59. 59. Why does the JIT matter for performance tests of a Java service?

    Correct answer: The first minutes run slower code until hot paths are compiled

    Warm up before measuring, or measure cold start separately when it matters for scaling.

  60. 60. What risk do @Disabled or enabled=false tests carry over time?

    Correct answer: They rot silently and the feature loses coverage

    Track disabled tests with a reason and a ticket, and review them regularly.

  61. 61. Why are records a good fit for API test DTOs?

    Correct answer: Concise, immutable, with value equality for easy assertions

    assertEquals(expectedUser, actualUser) works field by field, and toString shows all values on failure.

  62. 62. What does Optional.ofNullable(x).map(...).orElseThrow() express?

    Correct answer: Transform if present, or fail clearly if absent

    orElseThrow without args throws NoSuchElementException; pass a supplier for a clear message.

  63. 63. Why should integration tests clean up the data they create?

    Correct answer: Leftover data changes later tests and makes runs order-dependent

    Use transactions rolled back after the test, unique ids per run, or fresh containers.

  64. 64. What does Executors.newVirtualThreadPerTaskExecutor() change for I/O-heavy test drivers?

    Correct answer: Each task gets a cheap virtual thread, so thousands can wait

    Useful for load or API test tools that fire many concurrent requests.

  65. 65. Why does Arrays.asList(intArray) with an int[] surprise people?

    int[] nums = {1, 2, 3};
    List<int[]> list = Arrays.asList(nums);

    Correct answer: It returns a list with one element: the array itself

    Generics can't hold primitives, so T becomes int[]. Use IntStream.of(nums).boxed().toList().

  66. 66. Why should a test framework log the seed of random test data?

    Correct answer: To reproduce a failure with the same data later

    Random data finds bugs but must be repeatable. Print the seed on failure and allow passing it in.

  67. 67. What is the cost of synchronized on a hot shared method in a parallel test runner?

    Correct answer: Contention serializes threads and kills the speedup

    Profile before and after. Narrow the lock, use concurrent structures or per-thread state.

  68. 68. Why can a finally block hide the original exception?

    Correct answer: An exception thrown in finally replaces the one from try

    try-with-resources keeps the original and adds close() failures as suppressed exceptions.

  69. 69. When is CopyOnWriteArrayList a good choice?

    Correct answer: Many reads, rare writes, e.g. a list of listeners

    Each write copies the array; reads never lock and iterators never throw ConcurrentModificationException.

  70. 70. What does reflection-based test tooling need in a modular (JPMS) app?

    Correct answer: The package must be opened to the tool, e.g. via opens

    Frameworks like JUnit and Jackson use reflection. Without opens they fail with InaccessibleObjectException.

  71. 71. Why should you not rely on finalize() for cleanup?

    Correct answer: It's deprecated, may never run and delays freeing memory

    Use try-with-resources or Cleaner. Finalization is slated for removal.

  72. 72. What does jcmd <pid> Thread.print or a JFR recording help diagnose in a slow suite?

    Correct answer: Where threads spend time and what blocks them

    Java Flight Recorder adds low-overhead profiling of CPU, allocation and locks.

  73. 73. Why prefer Instant and UTC in test assertions on timestamps?

    Correct answer: Local time zones and DST make expected values machine-dependent

    Format in the user's zone only for display. Store and compare in UTC.

  74. 74. What does a 'golden master' (approval) test compare?

    Correct answer: Current output against a stored, reviewed snapshot

    Useful for legacy code with complex output; review snapshot changes like code.

  75. 75. Why is a shared mutable static WebDriver an anti-pattern in a parallel Java test suite?

    Correct answer: Tests on different threads drive the same browser and break each other

    Give each thread its own driver (ThreadLocal or a per-test fixture) and close it in teardown.