Skip to main content
InterviewHubPRO
HomeTracksSection 24: Java Core & JVM (50 Qs)
Section 24 of 6450 Questions (1 Per Page)

Core Java, JVM Internals, Memory Model & Concurrency Master Interview Bank

JVM architecture, G1GC/ZGC, Virtual Threads (Project Loom), JMM volatile/synchronized, Collections internals, CompletableFuture, NIO.2, and ClassLoaders.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Core Language, Memory Model & Collections (1 - 10)

10 Questions
1
JuniorCode#java#Core Language

What are the key differences between the JVM, JRE, and JDK, and what happens during Java bytecode execution?

JDK (Java Development Kit): The complete developer SDK containing compiler (javac), debugger, monitoring tools (jcmd, jconsole), and the JRE • JRE (Java Runtime Environment): The runtime libraries and the JVM needed to run compiled Java applications.

2
JuniorCode#Memory Management#Data Structures

Explain the JVM Memory Model: Heap vs. Stack vs. Metaspace.

Stack Memory: Thread-private, stores method call frames, primitive local variables, and object references • Heap Memory: Shared across all threads, stores all Java object instances and arrays • Metaspace: Native OS memory (replacing PermGen in Java 8+) that stores class metadata, method bytecode, and static constant pools.

3
SeniorCode#Memory Management

How does Garbage Collection work in modern Java (G1GC vs. ZGC)?

Java GC automatically recovers heap memory allocated to unreferenced objects using mark-and-sweep and copying algorithms: G1GC (Garbage-First GC): The default collector since Java 9 • ZGC (Z Garbage Collector): A low-latency, scalable collector in Java 17/21 designed for sub-millisecond pauses (< 1ms) regardless of heap size.

4
JuniorCode#Forms

What are Virtual Threads in Java 21 (Project Loom), and how do they differ from Platform Threads?

Platform Threads: 1:1 mapping to Operating System kernel threads • Virtual Threads: Lightweight user-space threads managed directly by the JVM (M:N mapping).

5
JuniorCode#java#Core Language

What are Java Records, Sealed Classes, and Pattern Matching?

Records (Java 16+): Immutable data carrier classes that automatically generate equals(), hashCode(), toString(), and private final fields • Sealed Classes (Java 17+): Restricts which classes or interfaces may extend or implement them using permits, enabling exhaustive compile-time.

6
JuniorCode#java#Core Language

What is the contract between `equals()` and `hashCode()`?

If two objects are equal according to equals(Object), their hashCode() must return the identical integer value • If two objects have the same hash code, they are NOT necessarily equal (hash collision) • If you override equals(), you MUST override hashCode().

7
Senior#java#Core Language

How does `HashMap` work internally in Java 8+?

HashMap is an array of buckets (Node[]).: Put: Computes hash(key) • Collision: If bucket is occupied, checks equals() • Treeification (Java 8+): If a bucket's linked list length exceeds TREEIFY_THRESHOLD (8) and array capacity is at least 64, the linked list.

8
JuniorCode#java#Core Language

What is the difference between `Comparable` and `Comparator`?

ComparableT: Defines natural ordering inside the class itself via int compareTo(T o) • ComparatorT: Defines custom, pluggable sorting strategies external to the class via int compare(T o1, T o2).

9
JuniorCode#java#Core Language

Explain the Java Memory Model (JMM): `volatile` vs. `synchronized` vs. `AtomicReference`.

volatile: Ensures visibility across CPU core caches and prevents compiler instruction reordering • synchronized: Ensures mutual exclusion (only one thread enters critical section at a time) AND memory visibility.

10
JuniorCode#java#Core Language

How do Java Streams work, and what is the difference between intermediate and terminal operations?

A Stream is a sequence of elements supporting functional-style pipeline operations: Intermediate Operations: Lazy; return a new Stream without executing (e.g., filter(), map(), sorted(), distinct()).

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

14 Questions
11
SeniorCode#System Design#Data Structures

What is the difference between ArrayList and LinkedList, and why is ArrayList almost always preferred?

ArrayList is backed by a contiguous, resizable array • LinkedList is a doubly linked list where each element is an independent object node holding references to the previous and next nodes • CPU Cache Locality (L1/L2/L3): Because ArrayList stores references in a contiguous block of memory, the CPU hardware prefetcher loads sequential.

12
SeniorCode#System Design

How does ConcurrentHashMap achieve high-throughput thread safety without locking the whole map in Java 8+?

Unlike Hashtable or Collections.synchronizedMap() which lock the entire map on every read or write, Java 8+ ConcurrentHashMap uses bucket-level fine-grained locking with CAS (Compare-And-Swap) and synchronized on the single root node of the target hash bucket.: Lock-Free Reads: Read operations (get()) are completely lock-free...

13
SeniorCode#System Design#Data Structures

What is CopyOnWriteArrayList and when should you choose it over synchronized lists?

A CopyOnWriteArrayList is a thread-safe List implementation where every write operation (add, set, remove) creates a brand-new internal copy of the underlying array.: Read-Heavy, Write-Rare: Perfect for observer/listener lists, system configuration caches, or routing tables where iterations happen thousands of.

14
SeniorCode#TypeScript#System Design

How does Type Erasure work in Java Generics and what are its runtime implications?

Type Erasure is the mechanism where the Java compiler enforces type constraints at compile time, but removes (erases) all generic type information when emitting bytecode (.class file). At runtime, generic types like ListString and ListInteger are identical: both are simply the raw type List.

15
SeniorCode#System Design

What is the difference between Runnable, Callable, and Future in Java Concurrency?

Runnable: Represents a task that runs asynchronously on a thread • CallableV: Represents an asynchronous computation • FutureV: Represents the eventual result of an asynchronous computation.

16
SeniorCode#Pipes#Async & Promises

How does CompletableFuture enable non-blocking asynchronous pipelines in Java 8+?

CompletableFutureT implements FutureT and CompletionStageT. It allows developers to compose complex asynchronous reactive pipelines with non-blocking callbacks, error recovery, and parallel aggregation without ever calling blocking .get().: thenApply(fn): Transforms the result synchronously when the stage completes (T \rightarrow U).

17
SeniorCode#System Design

How do you correctly configure and size ThreadPoolExecutor in production?

Never use Executors.newCachedThreadPool() (unbounded thread creation causes OOM) or Executors.newFixedThreadPool() (unbounded LinkedBlockingQueue exhausts memory under load).

18
SeniorCode#System Design

What are Java Reflection and MethodHandles, and why is MethodHandles faster?

Reflection (java.lang.reflect): Allows code to inspect classes, fields, and methods at runtime and invoke private members dynamically • MethodHandles (java.lang.invoke): Introduced in Java 7, MethodHandles provides typed, directly executable references to underlying methods.

19
SeniorCode#State Management#System Design

What is the difference between Java IO (Streams) and NIO.2 (Channels, Buffers, Selectors)?

Standard Java IO (java.io): Stream-oriented and blocking • Java NIO.2 (java.nio): Buffer-oriented and non-blocking.

20
SeniorCode#System Design

Why is standard Java Serialization considered harmful, and what are modern alternatives?

Java standard serialization (implements Serializable) automatically reconstructs arbitrary object graphs from binary streams without invoking class constructors, creating a massive remote code execution (RCE) vulnerability vector known as "deserialization gadget chains".

21
SeniorCode#Memory Management#System Design

What is the String Constant Pool and how does String.intern() affect heap memory?

The String Constant Pool is a specialized hashtable located in the Java Heap memory. When a string literal like "hello" is declared, the JVM checks if an identical string already exists in the pool.

22
SeniorCode#System Design

What are Strong, Soft, Weak, and Phantom References in Java and how do they interact with GC?

Java provides four levels of object reachability to give developers control over memory lifecycle: Strong Reference: Default reference (Object obj = new Object()) • Soft Reference (SoftReferenceT): Collected only when the JVM runs critically low on memory before throwing OutOfMemoryError.

23
Senior#System Design

What are final, finally, and finalize, and why was finalize() deprecated?

final: Keyword indicating immutability • finally: Block following a try-catch block that is guaranteed to execute regardless of whether an exception is thrown or caught (except in • finalize(): Deprecated method on java.lang.Object originally intended to clean up resources before an object was garbage-collected.

24
SeniorCode#System Design

What is Structured Concurrency and Scoped Values in Java 21+?

Structured Concurrency treats multiple tasks running in separate threads as a single unit of work, ensuring that child threads never outlive their parent scope. Scoped Values provide a safe, immutable alternative to ThreadLocal for sharing data across millions of virtual threads.

Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)

26 Questions
25
Senior#Golang

How does the JIT Compiler work (Tiered Compilation C1 vs C2) and what is Escape Analysis?

The JVM starts executing code via the Interpreter for instant startup. As methods are called thousands of times ("hot spots"), the JIT (Just-In-Time) Compiler compiles bytecode directly into native machine code (x86/ARM instructions).: Level 0 (Interpreter): Raw bytecode interpretation.

26
SeniorCode#Memory Management#Data Structures

How do you detect, analyze, and resolve a Java Memory Leak using Heap Dumps?

A Java memory leak occurs when objects are no longer needed by application logic, but remain reachable via an unintended strong reference path from a GC Root (e.g., static collections, unclosed listeners, un-cleared ThreadLocal variables in pooled threads).: Capture Heap Dump automatically on OOM.

27
SeniorCode#java#JVM Internals

What causes 100% CPU spikes in Java applications and how do you diagnose them using Thread Dumps?

100% CPU spikes in Java are typically caused by: GC Thrashing: When the heap is 99% full, GC threads run continuously in an infinite loop trying to free bytes before crashing with • Infinite Loops or Busy-Waiting: Threads spinning in lock-free CAS loops or bad while loops without yielding.

28
SeniorCode#Security & Auth

How does the Java ClassLoader hierarchy work and how does Parent Delegation prevent security breaches?

Java loads classes dynamically on-demand using a tree of ClassLoaders. Under the Parent Delegation Model, when a ClassLoader is requested to load a class, it always delegates the request to its parent ClassLoader first before searching its own classpath. #### Hierarchy.

29
SeniorCode#Memory Management

Compare G1GC, ZGC, and Shenandoah Garbage Collectors for high-throughput and low-latency systems?

G1GC (Garbage-First): The default collector since Java 9 • ZGC (Z Garbage Collector): Low-latency, scalable collector • Shenandoah: Ultra-low-latency collector developed by Red Hat.

30
Senior#java#JVM Internals

How does the Java Memory Model define happens-before relationships and instruction reordering?

Modern CPUs and compilers reorder machine instructions aggressively to maximize CPU pipeline execution throughput.

31
Senior#System Design#Apache Kafka

What is the LMAX Disruptor pattern and how does lock-free ring-buffer architecture achieve millions of ops/sec?

The LMAX Disruptor is a high-performance inter-thread messaging library that replaces standard BlockingQueue implementations to achieve tens of millions of operations per second with sub-microsecond latency.

32
SeniorCode#HTTP & REST APIs

What is the Foreign Function & Memory API (Project Panama) and how does it replace JNI?

Introduced in Java 22 as a final feature, the Foreign Function & Memory (FFM) API allows Java programs to safely interoperate with native C/C++ libraries and allocate off-heap memory without the fragile, unsafe, and slow machinery of JNI (Java Native Interface).: No C Glue Code Required: Bind directly to native shared libraries...

33
Most AskedSeniorCode#Docker & Containers#Kubernetes

How do you tune JVM flags for containerized microservices in Docker and Kubernetes?

Historically, the JVM inspected the host physical machine's RAM and CPU cores rather than the Linux cgroups limits set by Docker or Kubernetes, causing pods to be killed by the Linux OOM Killer. #### Essential Container Flags.

34
SeniorCode#Testing

How do you write reliable micro-benchmarks in Java using JMH (Java Microbenchmark Harness)?

Never benchmark Java code with System.currentTimeMillis() in a simple for loop! The JIT compiler optimizes away unused code (Dead Code Elimination), inlines methods dynamically, and distorts results during initial cold interpretation.

35
Senior#Docker & Containers

How does GraalVM Native Image compile Java to standalone native executables and what are its trade-offs?

GraalVM Native Image compiles Java bytecode Ahead-Of-Time (AOT) into a standalone platform-native binary (ELF executable) that includes application code, dependencies, and a stripped-down runtime called SubstrateVM.: Instant Startup: Sub-millisecond startup times (e.g., 10ms vs 3-5 seconds for standard JVM).

36
SeniorCode#System Design

Java Virtual Threads (Project Loom): Architecture and Best Practices.

Prior to Java 21, every java.lang.Thread was a heavyweight operating system (OS) kernel thread consuming \approx 1\text{MB} of stack memory, limiting concurrency to a few thousand threads.: Virtual Threads (Thread.ofVirtual()): Lightweight user-mode threads managed entirely by the JVM.

37
Senior#Memory Management

Modern Garbage Collectors: ZGC vs Shenandoah vs G1GC.

G1GC (Default): Divides heap into regional blocks • ZGC (Generational ZGC in Java 21+): Low-latency collector using colored pointers and load barriers • Shenandoah: Ultra-low-latency collector performing concurrent compaction alongside running Java application threads.

38
Senior#java#JVM Internals

Java Memory Model (JMM): `volatile` and Happens-Before Guarantees.

Modern CPUs have independent L1/L2 caches and reorder instructions for performance. The JMM defines rules for variable visibility across threads: volatile • Visibility: Guarantees that any write to a volatile variable is immediately flushed to main memory and visible to all other threads.

39
Senior#Memory Management#System Design

JVM Memory Architecture: Heap, Metaspace, and Stack.

JVM Stack: Thread-private • Heap Memory: Shared across all threads • Young Generation (Eden + Survivor S0/S1): Where new objects are allocated • Old (Tenured) Generation: Stores long-lived surviving objects.

40
SeniorCode#Async & Promises

`CompletableFuture` and Async Orchestration in Java.

CompletableFutureT represents an asynchronous computation supporting monadic chaining, error handling, and fan-out/fan-in combinations without blocking threads.

41
Senior#System Design

`ConcurrentHashMap` Concurrency Architecture.

Hashtable and Collections.synchronizedMap lock the entire table with a single synchronized lock, killing throughput • ConcurrentHashMap • In Java 7: Used 16 independent lock segments (Lock Striping).

42
Senior#java#JVM Internals

Java Dynamic Proxies vs Bytecode Manipulation (ByteBuddy / CGLIB).

Dynamic proxies create proxy classes at runtime: JDK Dynamic Proxy (Proxy.newProxyInstance): Built into the JDK • CGLIB / ByteBuddy: Subclasses concrete classes directly at runtime by generating raw JVM bytecode.

43
SeniorCode#java#JVM Internals

Modern Java Pattern Matching: Records, Sealed Classes, and Switch.

Java 17-21+ introduced algebraic data types: Records (record Point(int x, int y) {}): Immutable data carriers with auto-generated constructor, getters, equals(), and hashCode() • Sealed Classes (sealed interface Shape permits Circle, Square): Restricts which classes can extend or implement an interface.

44
Senior#HTTP & REST APIs

Foreign Function & Memory API (Project Panama).

Project Panama (Java 22+) replaces legacy Java Native Interface (JNI): Foreign Memory Access (Arena, MemorySegment): Safely allocates and accesses off-heap memory with deterministic allocation lifetimes, eliminating.

45
Senior#java#JVM Internals

Java Streams: Spliterators and Parallel Stream Traps.

A Spliterator partitions elements of a source for parallel execution • The Parallel Streams Trap: list.parallelStream() uses the shared common ForkJoinPool.commonPool().

46
Senior#Golang

Just-In-Time (JIT) Compilation: Tiered Compilation and Escape Analysis.

The HotSpot JVM interprets bytecode initially, while profiling execution: C1 Compiler (Client): Quickly compiles hot methods with basic optimizations • C2 Compiler (Server / Graal): Heavily optimizes hot methods (loop unrolling, method inlining, branch prediction).

47
Senior#Performance

Low-Overhead Profiling: JDK Flight Recorder (JFR).

JDK Flight Recorder (JFR) is a kernel-integrated, low-overhead (< 1\% CPU impact) diagnostic engine built directly into the JVM. It records CPU usage, thread locks, memory allocations, garbage collection pauses, and socket I/O, allowing developers to safely diagnose live production incidents without degrading user latency.

48
Senior#java#JVM Internals

Scoped Values (JEP 446): Replacing `ThreadLocal` for Virtual Threads.

ThreadLocal stores mutable state per thread. With 1,000,000 virtual threads, millions of ThreadLocal maps consume massive heap memory and risk leaks if not manually cleaned up.: Scoped Values (ScopedValue.where(...)): Immutable, stack-bounded values shared safely across virtual threads and child tasks with guaranteed.

49
Senior#java#JVM Internals

The Java Module System (JPMS / Project Jigsaw).

Introduced in Java 9 (module-info.java): Provides Strong Encapsulation: Internal implementation packages cannot be accessed by external consumers, even via reflection! • Explicit dependency graphs via requires and exports.

50
Senior#Forms#Performance

High-Performance Java Networking: Java NIO vs Netty.

Java NIO (Non-blocking I/O): Uses SocketChannel and Selector to manage thousands of active network sockets with a handful of threads • Netty: Production-grade async event-driven framework built on top of NIO • Custom memory buffer (ByteBuf) with reference counting and thread-local pooling.