Top 40 Garbage Collection Interview Questions | Must-Prepare before interview.
Top 40 Garbage Collection Interview Questions | Must-Prepare before interview Work through these 40 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.
What is an ExecutorService and why use it?
Instead of new Thread per task, submit Runnable to fixed pool sized to CPU/IO profile. Handle Future results and exceptions. On shutdown hook call shutdown() and...
What are virtual threads in Java 21 and when should you use them?
Virtual threads excel when code blocks on IO — HTTP clients, JDBC, file reads — allowing one platform thread to serve thousands of concurrent requests. For CPU-heavy parallel...
Explain sealed classes and their purpose in Java 17+.
sealed interface Shape permits Circle, Rectangle limits who implements Shape. Compiler verifies switch (Shape s) covers all cases — no default needed. Use for domain variants...
What is pattern matching for switch (Java 21)?
Instead of if (obj instanceof String s) { ... }, use switch (obj) { case String s when s.length() > 5 -> ...; case String s -> ...; case null -> ...; default -> ... }. Works...
When should you use CopyOnWriteArrayList?
Use for subscriber lists in pub/sub where adds are rare and iteration is constant. Avoid for high-frequency add/remove — use ConcurrentLinkedQueue or synchronized collections....
What are text blocks and how do they improve Java code?
String query = """ SELECT u.id, u.name FROM users u WHERE u.active = true """; — readable without \n concatenation. Use formatted for parameters carefully — prefer...
Explain structured concurrency and why it matters.
In a request handler, open StructuredTaskScope, fork fetchUser and fetchOrders, join both — if orders fail, user fetch cancelled automatically. Safer than manual Future...
Explain immutability and why String is immutable.
Immutable objects cannot change after build — thread-safe without synchronization. String immutability allows intern pool, caching hashCode, and security when used as...
Explain garbage collection basics in the JVM.
New objects allocate in Eden; minor GC copies survivors to survivor spaces, then old gen. When old gen fills, major/full GC runs — longer pauses. Tune -Xmx, choose G1 for...
Why is ThreadLocal problematic with virtual threads?
Libraries storing per-request state in ThreadLocal allocate one entry per virtual thread — catastrophic memory with 100k concurrent requests. Prefer ScopedValue for request...
How do CompletableFuture and virtual threads compare for concurrency?
Use virtual threads when business logic is naturally blocking — call DB, call HTTP, return. Use CompletableFuture when composing multiple independent async results with...
Explain the happens-before relationship in the Java Memory Model.
Thread A writes x=1 without sync; Thread B reads x may see 0 forever. volatile x or synchronized block creates happens-before. Classic DCL singleton needs volatile instance...
What are weak references and WeakHashMap use cases?
Attach metadata to objects without extending their lifetime — canonical mapping while object lives. When key GCs, entry drops. Do not rely on timing. For API response caching...
What are GraalVM native image considerations for Spring Boot?
Use spring-boot-maven-plugin native profile + GraalVM 21. Run integration tests on native binary. Register reflection for Jackson/custom serializers. Trade longer CI builds for...
Compare G1, ZGC, and Shenandoah garbage collectors.
Default G1 fine for most Spring Boot services — tune -XX:MaxGCPauseMillis=200. Payment API p99 SLA <10ms GC pause: try -XX:+UseZGC on Java 21 large heap. Benchmark with JMH and...
What is Metaspace and how do class loading issues cause memory leaks?
Production set MaxMetaspaceSize 256m with monitoring. Investigate Metaspace OOM: heap dump + classloader histogram. Avoid generating unlimited dynamic proxies. OSGi/script...
JVM container awareness and memory settings for Kubernetes?
Container limit 1Gi: JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75.0 -XX:InitialRAMPercentage=50.0. Monitor container memory vs heap used in Actuator metrics. Leave headroom for...
A REST API is slow only in production, not locally. How do you debug it?
Enable Micrometer timers and Hibernate statistics or datasource-proxy in staging with prod-like data. Check Hikari `connections-active`, JVM GC pauses, and Feign/RestClient...
Your Spring Boot service crashes under high traffic. What could be the reasons?
Common causes: too-small heap (`-Xmx`), Hikari pool smaller than concurrent requests, blocking calls on limited threads, missing backpressure. Fix: tune...
Your application memory usage keeps increasing over time. What do you suspect?
Suspect memory leak if heap used grows after GC without traffic drop. Capture heap dump on OOM (`-XX:+HeapDumpOnOutOfMemoryError`), compare dominator tree. Common in Spring:...
API returns correct data but response time is inconsistent. Why?
Tail latency often from stop-the-world GC, connection pool contention, or cold cache. Monitor p99 separately from mean. ```yaml spring.datasource.hikari.maximum-pool-size: 10...
Your Spring Boot app fails only when deployed in Docker. Why?
Container `-Xmx256m` with 256Mi limit causes OOMKilled. Missing `DB_HOST` defaults to localhost inside container. ```dockerfile ENV JAVA_OPTS="-XX:MaxRAMPercentage=75.0" ```...
New deployment causes random 5xx errors. Rollback fixes it. Why?
Compare metrics before/after: error rate, pool saturation, GC. Enable DEBUG temporarily in canary pod only. Check new dependency version, connection pool default change, or...
When do useMemo and useCallback actually help — and when do they make things worse?
I memoize a filtered 10k-row list or a value passed into a memoized DataGrid. I do not wrap every onClick. Profiler + why-did-you-render first. In React 19 I let the compiler...
Why is storing a JWT in localStorage a problem, and what do you do instead with Spring Security?
I prefer BFF: Vite proxies /api, Spring sets httpOnly cookie, React never sees the JWT. If I must use a bearer token, I keep access token in memory and refresh via cookie. I...
Which JVM and library changes in JDK 15 show up in production ops, not just language trivia?
If we touched 15 on the way to 17/21, I check three ops items: collector is no longer experimental so flags change, ZGC may uncommit so RSS graphs look different, and any...
What did generational ZGC change in JDK 21, and when would you pick it over G1?
For a large-heap, latency-sensitive API I trial generational ZGC in staging: p99 pause, allocation rate, and RSS. I keep G1 if throughput or CPU is the SLO. I never flip...
Why would a team pin JDK 25 LTS after 21, and what would you verify in staging besides language features?
I pin 25 when the Boot version supports it, agents are certified, and staging GC/heap histograms look at least as good as 21. I turn on compact headers in a canary if we care...
JDK 27 is not LTS. What do you inherit on upgrade without writing new application code?
I would not pin 27 as LTS — 25 is still the pin. On a 27 canary I inherit G1 in CI that used to pick Serial, compact headers, and hybrid TLS if the JDK terminates TLS. I...
Why did JDK 27 make G1 the default GC everywhere, and when would you still pick Serial or ZGC?
First I check the collector in the new CI log. If it flipped Serial → G1, that is JEP 523 — not a 27 regression. I keep G1 in prod with equal heap and a pause goal. I only...
What is AiServices, and why is it better than calling chat.completions() from a controller?
AiServices is a typed facade over ChatLanguageModel. I declare TicketAssistant with @SystemMessage and @UserMessage, register it as a singleton @Bean, and the controller never...
What is Anthropic prompt caching in LangChain4j 1.22.0, and when is it worth turning on?
I put the interviewer persona, tool JSON, and the static policy appendix in the cached system prefix. The user question and this-request RAG chunks stay dynamic. If the prefix...
Explain the difference between == and .equals() in Java.
For primitives, == compares values. For objects, == asks if two references point to the same instance. equals() compares content when overridden — String overrides it for...
HashMap vs ConcurrentHashMap — when and why?
HashMap for single-threaded or external synchronization. ConcurrentHashMap for shared concurrent maps — finer-grained locking than Hashtable. Cannot store null keys/values in...
What is the difference between ArrayList and LinkedList?
ArrayList: dynamic array, great for get(i) and iteration, amortized append. LinkedList: node chain, costly random access, only wins for frequent insert/remove in middle with...
What is the difference between Comparable and Comparator?
Comparable built into the type — Employee implements compareTo by id. Comparator external — sort by name or salary without changing Employee. Use...
volatile vs synchronized — when to use each?
volatile for single-writer flags (shutdown, initialized) where no read-modify-write. synchronized or java.util.concurrent locks when multiple threads update shared state. For...
What is Optional and when should you use it?
Use Optional as return type when absence is expected — findById returns Optional<User>. Chain with map/flatMap/orElseThrow. Do not use for fields, method parameters, or Jackson...
Explain method overloading vs overriding.
Overload print(int) and print(String) in one class — compiler picks at compile time. Override toString in subclass — JVM calls subclass version via virtual method table....
How does Stream API parallel stream work?
parallelStream() splits work across common pool threads. Good for CPU-heavy map on large in-memory collections. Bad for small lists, IO inside stream, or ordered stateful...
Garbage Collection Interview Questions and Answers · Top 50 Garbage Collection Interview Questions and Answers (2026 Edition) · Garbage Collection Interview Questions Every Fresher Must Know · Garbage Collection Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform