Advanced Java Interview Q&A
40 Essential Concepts for Senior Developers
Question 1
How does HashMap handle collisions in Java 8?
When two keys map to the same bucket, HashMap stores them together. Initially, it
uses a linked list to manage collisions. If the list becomes too long (≥8), it converts
into a Red-Black Tree. This improves lookup performance significantly. So worst-
case time improves from O(n) to O(log n).
Question 2
Why is volatile not enough for thread safety? (code)
Volatile ensures all threads see the latest value. But it does not make operations like
increment atomic. Multiple threads can still overwrite each other’s updates. So race
conditions can still happen. Use Atomic classes or synchronization instead.
volatile int count = 0;
count++; // unsafe
AtomicInteger c = new AtomicInteger();
[Link](); // safe
Question 3
What is happens-before in simple terms?
It’s a rule that guarantees execution order between threads. If one operation
happens-before another, the second sees the first’s result. It ensures memory
visibility across threads. Used in locks, volatile, and thread operations. Without it,
programs behave unpredictably.
Question 4
Why use ConcurrentHashMap instead of HashMap? (code)
HashMap is not safe when multiple threads use it. ConcurrentHashMap allows
multiple threads to work together safely. It locks only small parts instead of the
whole map. This improves performance in concurrent environments. That’s why it’s
widely used in real applications.
ConcurrentHashMap map = new ConcurrentHashMap<>();
[Link]("key", 1);
Question 5
What is deadlock in simple terms? (code)
Deadlock happens when two threads wait for each other forever. Each thread holds
a lock that the other needs. So both are stuck and cannot proceed. It’s a common
concurrency issue. Avoid by keeping lock order consistent.
synchronized(lock1) {
synchronized(lock2) {
// safe if order same everywhere
}
}
Question 6
What is ThreadLocal and when to use it? (code)
ThreadLocal gives each thread its own copy of a variable. So threads don’t interfere
with each other’s data. Useful for user sessions or database connections. It avoids
synchronization overhead. But must be cleaned to prevent memory leaks.
ThreadLocal local = [Link](() -> 0);
[Link](10);
Question 7
What is CompletableFuture? (code)
It is used for asynchronous programming. It lets you run tasks without blocking
threads. You can chain multiple operations easily. Improves performance in backend
systems. Part of Java 8 concurrency features.
[Link](() -> "Hi")
.thenApply(s -> s + " Java");
Question 8
Why is String immutable?
Strings are used in many critical areas like security and caching. If they were
mutable, it could cause bugs and vulnerabilities. Immutability makes them thread-
safe automatically. It also enables string pooling for memory efficiency. So Java
keeps Strings constant after creation.
Question 9
What is double-checked locking? (code)
It is used to create Singleton efficiently. It checks instance before and after locking.
Reduces unnecessary synchronization. Requires volatile to avoid reordering issues.
Ensures only one instance is created.
if(instance == null){
synchronized([Link]){
if(instance == null)
instance = new Class();
}
}
Question 10
What is Stream API in simple words? (code)
Stream API processes collections in a functional style. It uses pipelines of
operations like filter and map. Execution is lazy until terminal operation is called. It
reduces boilerplate code. Also supports parallel processing.
[Link]()
.filter(x -> x > 10)
.map(x -> x * 2)
.toList();
Question 11
What is Java Memory Model (JMM)?
JMM defines how threads interact with memory. It ensures visibility, ordering, and
atomicity. Threads may cache values locally, causing issues. Happens-before rules
solve this problem. It is essential for writing correct concurrent code.
Question 12
What is false sharing?
It happens when threads modify nearby variables. These variables share the same
CPU cache line. This causes frequent cache invalidation. Performance drops
significantly. Solved by separating or padding variables.
Question 13
What is escape analysis?
It is a JVM optimization technique. It checks if an object escapes method scope. If
not, it may allocate it on stack. This reduces heap usage and GC overhead. Also
enables lock optimization.
Question 14
What is lock contention?
Occurs when multiple threads compete for same lock. Only one thread can proceed
at a time. This reduces system performance. Common in synchronized blocks. Can
be reduced using better design or concurrent tools.
Question 15
What is ForkJoinPool?
It is used for parallel task execution. Large tasks are divided into smaller ones.
Threads process tasks and combine results. Uses work-stealing for efficiency. Best
for CPU-intensive operations.
Question 16
What is immutability advantage?
Immutable objects cannot be changed. So they are naturally thread-safe. No need
for synchronization. Safe to share across threads. Improves performance and
reliability.
Question 17
What is GC reachability analysis?
GC checks which objects are reachable. Starts from root references like stack and
static fields. Objects not reachable are collected. Ensures memory cleanup.
Prevents accidental deletion of active objects.
Question 18
What is Optional in Java?
Optional is a container for nullable values. It avoids NullPointerException.
Encourages explicit handling of missing values. Provides methods like orElse and
map. Improves code readability.
Question 19
What is deadlock prevention technique? (code)
Always acquire locks in same order. Avoid nested locks when possible. Use tryLock
with timeout. Reduce synchronized scope. Careful design avoids deadlock.
[Link]();
[Link]();
Question 20
What is Executor Framework?
It manages thread pools efficiently. Separates task submission from execution.
Improves scalability and performance. Provides ready-made thread pool types. Used
in most concurrent applications.
Question 21
What is CAS (Compare-And-Swap)? (code)
CAS is a lock-free technique. It updates value only if expected value matches. Used
in Atomic classes. Avoids blocking threads. Improves performance in concurrency.
AtomicInteger a = new AtomicInteger(1);
[Link](1, 2);
Question 22
What is AQS (AbstractQueuedSynchronizer)?
It is a framework for building locks. Manages thread queue internally. Used in
ReentrantLock and Semaphore. Handles synchronization state. Simplifies
concurrency design.
Question 23
What is safe publication?
Ensures object is visible correctly to all threads. Prevents partially constructed
objects. Achieved using final, volatile, or sync. Important in shared objects. Avoids
hidden concurrency bugs.
Question 24
What is livelock?
Threads keep running but make no progress. They keep reacting to each other.
Unlike deadlock, threads are active. Common in retry logic. Solved using delays or
backoff.
Question 25
What is starvation?
A thread never gets CPU time. Other threads keep dominating resources. Occurs due
to priority issues. Leads to indefinite waiting. Solved using fair scheduling.
Question 26
What is method inlining?
JIT replaces method calls with actual code. Reduces function call overhead.
Improves performance. Applied to small, frequent methods. Part of JVM
optimization.
Question 27
What is classloader delegation model?
Classes are loaded in parent-first order. Child asks parent before loading class.
Ensures core classes are safe. Prevents malicious class override. Maintains security
and consistency.
Question 28
What is serialization risk?
Untrusted data can execute malicious code. Leads to security vulnerabilities.
Requires validation and filtering. Used carefully in applications. Important in
distributed systems.
Question 29
What is NIO vs IO?
IO is blocking and thread-per-task. NIO is non-blocking and scalable. Uses channels
and buffers. Better for high-performance systems. Used in servers and networking.
Question 30
What is backpressure?
Controls flow of data in systems. Prevents overload when producer is faster. Used in
reactive programming. Ensures stability. Handled via buffering or throttling.
Question 31
What is GC pause?
Application threads stop during GC. Called stop-the-world event. Affects application
performance. Reduced using modern GC algorithms. Important in low-latency
systems.
Question 32
What is object pooling drawback?
Adds complexity to code. May cause memory overhead. Not always needed with
modern JVM. Better to rely on GC. Used only for heavy objects.
Question 33
What is reflection drawback?
Slower than direct method calls. Breaks encapsulation. Harder to maintain. Used in
frameworks mostly. Avoid excessive use.
Question 34
What is functional programming in Java?
Introduced with Java 8. Uses lambdas and streams. Focuses on immutability.
Reduces side effects. Improves readability.
Question 35
What is parallel stream risk? (code)
Parallel streams use multiple threads. Not safe with shared mutable data. May
cause race conditions. Overhead may reduce performance. Use only for CPU-heavy
tasks.
[Link]().forEach([Link]::println);
Question 36
What is heap fragmentation?
Memory gets divided into small pieces. Large objects cannot be allocated easily.
Reduces efficiency. Handled by GC compaction. Common in long-running apps.
Question 37
What is class initialization order?
Static variables and blocks run first. Then instance variables. Then constructor
executes. Parent class loads first. Ensures proper object setup.
Question 38
What is dynamic proxy? (code)
Creates proxy objects at runtime. Intercepts method calls. Used in Spring and AOP.
Reduces boilerplate code. Uses Proxy class.
[Link](
[Link]().getClassLoader(),
[Link]().getInterfaces(),
handler
);
Question 39
What is JVM warm-up?
Initial execution is slower. JIT optimizes code over time. Performance improves
after repeated runs. Affects benchmarking. Handled using proper tools.
Question 40
What is lock striping?
Uses multiple locks instead of one. Reduces contention. Improves concurrency.
Used in older ConcurrentHashMap. Balances performance and complexity.