Wednesday, July 22, 2026

Java Multi Threading interview questions




Differentiate concurrency and parallelism


Concurrency

Parallelism

Multiple tasks interleaved

Multiple tasks simultaneously

Improves responsiveness

Improves execution speed

Single or multiple cores

Requires multiple CPU cores

Context switching involved

Tasks execute concurrently

Focuses on task management

Focuses on task execution




How to create a multiple Threads 


Extend Thread class

Implement Runnable interface

Implement Callable interface

Use ExecutorService thread pool

Use CompletableFuture API


JVM


Each thread owns stack

Heap shared across threads

Program counter per thread

Monitors manage synchronization

JMM ensures memory visibility



Thread stack


  1. Stores method call frames
  2. Each thread owns one
  3. Holds local variables
  4. Tracks method execution
  5. Created with thread start


program counter


  1. Stores current instruction address
  2. Each thread owns one
  3. Tracks execution progress
  4. Updated after every instruction
  5. Enables thread context switching


Volatile Keyword :

Ensures variable visibility always

Reads latest memory value

Prevents instruction reordering

Doesn't guarantee atomicity

No mutual exclusion provided


Problems with volatile  

  1. No atomicity for operations
    count++ involves read → modify → write, so multiple CPUs can overwrite each other's updates even though the variable is volatile.
  2. Cache coherence overhead
    Every volatile write invalidates cached copies in other CPU cores, increasing cache traffic and reducing performance.
  3. Memory fence overhead
    volatile inserts CPU memory barriers (fences), preventing instruction reordering and slowing execution.
  4. No mutual exclusion
    Multiple CPU cores can still execute the same code simultaneously; volatile only guarantees visibility, not exclusive access.
  5. Not suitable for compound operations
    Operations like increment, check-then-act, or read-modify-write require synchronization or atomic classes because volatile cannot prevent race conditions.

synchronized


  1. Provides mutual exclusion
  2. Uses object or class monitor
  3. Automatically releases lock
  4. Prevents race conditions
  5. Ensures memory visibility

wait()

  1. Releases object's monitor lock
  2. Thread enters waiting state
  3. Waits until notification
  4. Must own monitor
  5. Called inside synchronized

notify()

  1. Wakes one waiting thread
  2. Doesn't release lock immediately
  3. Must own monitor
  4. Called inside synchronized
  5. Thread competes for lock


How can deadlock happen



  1. Competing resource acquisition order
  2. Each thread holds lock
  3. Waiting for another lock
  4. Circular dependency between threads
  5. No thread can proceed

 Class Lock

Locks entire class object

Shared across all instances

Acquired by static methods

Uses Class object monitor

One thread enters only 

Object Lock



  1. Locks individual object instance
  2. Each object has monitor
  3. Acquired by synchronized methods
  4. Different objects lock independently
  5. One thread per object


Fail Fast vs Fail Safe Iterator

 



Fail-Fast Iterator

Fail-Safe Iterator

Iterates original collection

Iterates collection snapshot

Detects concurrent modifications

Allows concurrent modifications

Throws ConcurrentModificationException

No ConcurrentModificationException

Reflects latest collection state

Reflects copied collection state

Faster, lower memory overhead

Slower, extra memory usage

Examples:

  • Fail-Fast: ArrayList, HashMap, HashSet
  • Fail-Safe: ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentSkipListMap


Explain the differences between Deadlock and Livelock



 

Aspect

Deadlock

Livelock

Definition

Two or more threads are permanently blocked, each waiting for a resource held by another.

Two or more threads keep changing state in response to each other but never make progress.

Thread State

Usually BLOCKED or WAITING.

Usually RUNNABLE; threads are actively executing.

CPU Usage

Low (threads are blocked).

High (threads keep running).

Progress

No progress because threads are waiting.

No progress because threads keep retrying or yielding.

Cause

Circular resource dependency.

Overly polite or repeated retry logic where threads continuously avoid each other.

Example

Thread A holds Lock1 and waits for Lock2, while Thread B holds Lock2 and waits for Lock1.

Thread A releases a lock when it detects Thread B needs it, while Thread B does the same, causing both to endlessly back off.

Detection

Easy to detect using thread dumps (jstack), JVM deadlock detection, or VisualVM.

Harder to detect because threads appear active.

Resolution

Use lock ordering, timeouts, avoid nested locks, or use tryLock().

Introduce random backoff, retry delays, or asymmetric retry strategies.



How does ConcurrentHashMap achieve thread-safety ?

CAS for lock-free updates

Per-bucket synchronized locking

Volatile memory visibility guarantees

Atomic compound map operations

Concurrent reads without locking




Explain the differences between synchronized, ReentrantLock, and ReadWriteLock.

 


synchronized

ReentrantLock

ReadWriteLock

JVM-managed intrinsic lock

Explicit lock implementation

Separate read/write locks

Automatic lock release

Manual unlock() required

Manual unlock() required

No fairness option

Supports fair locking

Supports fair locking

No interruptible lock

Interruptible lock acquisition

Interruptible lock acquisition

Exclusive access only

Exclusive access only

Concurrent readers allowed





Differentiate between Runnable, Callable


 


Runnable

Callable

No return value

Returns a value

Cannot throw checked exceptions

Can throw checked exceptions

run() method

call() method

Used with Thread

Used with ExecutorService

Returns void

Returns Future<T>


Executor


  1. Executes submitted tasks
  2. Decouples task execution
  3. Abstracts thread management
  4. Uses thread pool implementations
  5. Improves resource utilization


ExecutorService


  1. Manages thread pool lifecycle
  2. Executes asynchronous tasks
  3. Returns Future results
  4. Supports graceful shutdown
  5. Reuses worker threads

Executors


  1. Factory for thread pools
  2. Creates ExecutorService instances
  3. Provides predefined pool types
  4. Simplifies thread pool creation
  5. Avoids manual configuration


ThreadPoolExecutor


  1. Manages reusable worker threads
  2. Executes submitted tasks efficiently
  3. Reduces thread creation overhead
  4. Supports configurable pool size
  5. Queues excess submitted tasks



Reenterant Lock



  1. Explicit lock implementation
  2. Supports lock reentrancy
  3. Requires manual unlock()
  4. Supports fair scheduling
  5. Provides interruptible locking


ReadWrite Lock

Separate read and write locks

Multiple readers access concurrently

Only one writer allowed

Writers block all readers

Improves read-heavy performance



Explain Compare and swap


  1. Atomic CPU instruction
  2. Compares expected memory value
  3. Updates if values match
  4. Retries when comparison fails
  5. Enables lock-free synchronisation


Future


  1. Represents asynchronous task result
  2. Retrieves result using get()
  3. Blocks until completion
  4. Supports task cancellation
  5. Cannot chain dependent tasks


Completion stage


  1. Represents asynchronous computation stage
  2. Depends on previous stage
  3. Chains multiple asynchronous operations
  4. Supports callback-based processing
  5. Implemented by CompletableFuture


completable future


  1. Implements Future<T> and CompletionStage<T>
  2. needs an ExecutorService because it does not create or manage its own threads
  3. Performs asynchronous computations
  4. Chains dependent asynchronous tasks
  5. Combines multiple task results
  6. Handles exceptions asynchronously
  7. Avoids blocking main thread


No comments:

Post a Comment

Java Garbage Collection Interview Questions

JVM Executes Java bytecode Provides platform independence Manages memory automatically Handles garbage collection Runs Java application...