Wednesday, July 22, 2026

Java Multi Threading interview questions




Differentiate concurrency and parallelism
ConcurrencyParallelism
Multiple tasks interleavedMultiple tasks simultaneously
Improves responsivenessImproves execution speed
Single or multiple coresRequires multiple CPU cores
Context switching involvedTasks execute concurrently
Focuses on task managementFocuses 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
  • 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 IteratorFail-Safe Iterator
    Iterates original collectionIterates collection snapshot
    Detects concurrent modificationsAllows concurrent modifications
    Throws ConcurrentModificationExceptionNo ConcurrentModificationException
    Reflects latest collection stateReflects copied collection state
    Faster, lower memory overheadSlower, extra memory usage

    Examples:

    • Fail-Fast: ArrayListHashMapHashSet
    • Fail-Safe: ConcurrentHashMapCopyOnWriteArrayListConcurrentSkipListMap

    Explain the differences between Deadlock and Livelock

     
    AspectDeadlockLivelock
    DefinitionTwo 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 StateUsually BLOCKED or WAITING.Usually RUNNABLE; threads are actively executing.
    CPU UsageLow (threads are blocked).High (threads keep running).
    ProgressNo progress because threads are waiting.No progress because threads keep retrying or yielding.
    CauseCircular resource dependency.Overly polite or repeated retry logic where threads continuously avoid each other.
    ExampleThread 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.
    DetectionEasy to detect using thread dumps (jstack), JVM deadlock detection, or VisualVM.Harder to detect because threads appear active.
    ResolutionUse 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 synchronizedReentrantLock, and ReadWriteLock.

     

    synchronizedReentrantLockReadWriteLock
    JVM-managed intrinsic lockExplicit lock implementationSeparate read/write locks
    Automatic lock releaseManual unlock() requiredManual unlock() required
    No fairness optionSupports fair lockingSupports fair locking
    No interruptible lockInterruptible lock acquisitionInterruptible lock acquisition
    Exclusive access onlyExclusive access onlyConcurrent readers allowed




    Differentiate between RunnableCallable

     
    RunnableCallable
    No return valueReturns a value
    Cannot throw checked exceptionsCan throw checked exceptions
    run() methodcall() method
    Used with ThreadUsed with ExecutorService
    Returns voidReturns 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


  • Java Multi Threading interview questions

    Differentiate concurrency and parallelism Concurrency Parallelism Multiple tasks interleaved Multiple tasks simultaneously Improves responsi...