Top 40 Java Multithreading Interview Questions | Must-Prepare before interview.
Top 40 Java Multithreading 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.
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...
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...
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...
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....
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...
AtomicReference vs synchronized — when to choose each?
Use AtomicReference for lock-free config pointer swap — compareAndSet(old, new). Use synchronized when updating multiple related fields atomically. AtomicInteger for counters....
IdentityHashMap vs HashMap — when would you use IdentityHashMap?
Use when identity matters not value — tracking object visitation in deep graph walk. Business keys (userId, email) belong in HashMap with proper equals/hashCode....
What are ScopedValues and how do they replace ThreadLocal?
Replace logging MDC ThreadLocal with ScopedValue.where(REQUEST_ID, id).run(() -> handle()). Value immutable — update by nesting new scope. Frameworks (Spring, Micrometer)...
What is ForkJoinPool common pool starvation and how do you avoid it?
Never block on common pool — no DB/HTTP in parallelStream without custom pool. Use Executors.newFixedThreadPool for blocking batch jobs. CompletableFuture.supplyAsync(task,...
How do you enable virtual threads in Spring Boot 3.2+?
application.yml: spring.threads.virtual.enabled=true on Java 21. Verify integration tests pass — especially security, transactions, MDC logging. Replace custom fixed thread...
How do JPA Specifications (Criteria API) help dynamic queries?
UserSearchSpec.withStatus(status).and(withNameLike(name)) — repository.findAll(spec, pageable). Criteria API verbose — wrap in static factory methods. Alternative: Querydsl or...
How implement multi-tenancy in Spring Security context?
JWT includes tenant_id — converter sets TenantContextHolder. Base entity @Column tenantId validated on save. Repository methods always include tenant predicate — or Hibernate...
Load shedding and backpressure in microservices?
Tomcat max queue + reject policy returns 503 with Retry-After. WebClient timeout + circuit breaker stops calling slow dependency. Kafka consumer pause partitions when...
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...
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:...
One microservice is down and others are failing. How do you prevent this?
Cascade failure happens when callers block waiting. Use Resilience4j circuit breaker — open circuit fails fast with degraded response. ```java @CircuitBreaker(name = "catalog",...
How do you handle long-running background jobs in Spring Boot?
Do not block HTTP threads. Use `@Async` with named executor or message-driven workers. ```java @EnableAsync @Configuration public class AsyncConfig { @Bean Executor...
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...
Database is healthy but app shows connection timeout. Why?
DB healthy from admin console but app waits for free connection. Check Hikari pending threads. ```yaml spring.datasource.hikari.maximum-pool-size: 10...
Why is JDK 21 the LTS pin for Spring Boot 3.2+, and when are virtual threads the wrong default?
We pin JDK 21 because it is LTS and Boot 3.2+ is built for it. I turn on virtual threads for blocking I/O APIs, keep Hikari at a DB-safe size, and put a Semaphore bulkhead in...
JDK 25 ScopedValue vs ThreadLocal — what changes in a thread-pool or virtual-thread service?
Request tenant, correlation id, and security principal go in a ScopedValue.where(CTX, ctx).run(...) around the work. I do not set ThreadLocal in a filter and hope finally runs....
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...
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...
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...
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....
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...
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 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...
What is the Java Platform Module System (JPMS) and who needs it?
Use modules when building custom JDK images or publishing strict API boundaries. Typical microservice: no module-info — Spring Boot repackages classpath. Watch for illegal...
Compare BlockingQueue implementations for producer-consumer workloads.
For order processing, use ArrayBlockingQueue with capacity matching SLA — slow consumer blocks producer instead of OOM. ThreadPoolExecutor with SynchronousQueue +...
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...
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...
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...
Java Multithreading Interview Questions and Answers · Top 50 Java Multithreading Interview Questions and Answers (2026 Edition) · Java Multithreading Interview Questions Every Fresher Must Know · Java Multithreading Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform