HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
75 Topics
Chapter•390 Minutes

Java Progressive Master Question Bank

75 progressive Java interview questions complete with technical explanations, key takeaways, diagrams, code examples, and interactive knowledge check quizzes.

Q41: What are the states in the Java Thread Lifecycle?

  1. NEW: Thread instantiated, start() not yet called.
  2. RUNNABLE: Executing or eligible for execution in OS scheduler pool.
  3. BLOCKED: Waiting to acquire a monitor lock (synchronized block).
  4. WAITING: Waiting indefinitely for another thread action (Object.wait(), Thread.join()).
  5. TIMED_WAITING: Waiting for a specified time duration (Thread.sleep(ms), wait(ms)).
  6. TERMINATED: Execution completed.
Java Thread State Transitions
Key Takeaways
  • BLOCKED = Waiting to acquire a monitor lock. WAITING = Waiting for thread signal notification.
Knowledge Check

Which state does a thread enter when waiting to acquire a synchronized block lock held by another thread?

Q42: What are the differences between Runnable and Callable interfaces?

  • Runnable: public void run(). Cannot return a result value; cannot throw checked exceptions.
  • Callable<V>: public V call() throws Exception. Returns a generic result V; allowed to throw checked exceptions. Used with ExecutorService and Future.
Key Takeaways
  • Runnable: Returns void, handles no checked exceptions. Callable: Returns generic value V, throws checked exceptions.
Knowledge Check

Which interface should be used for background asynchronous tasks that MUST return a calculation result?

Q43: How does the synchronized keyword work under the hood using Intrinsic Monitors?

Every Java Object possesses an Intrinsic Lock (Monitor).

  • Synchronized Instance Method: Locks on this object instance.
  • Synchronized Static Method: Locks on the class Class object (TargetClass.class).
  • Synchronized Block: Locks on a specified reference object. Under bytecode execution, monitorenter acquires the monitor and monitorexit releases it, ensuring mutual exclusion and cache flushing.
Key Takeaways
  • Enforces mutual exclusion across threads accessing shared state.
  • Uses bytecode monitorenter / monitorexit directives on Object monitors.
Knowledge Check

What monitor object is locked when executing a synchronized static method?

Q44: What does the volatile keyword guarantee (Visibility vs Atomicity)?

volatile guarantees Memory Visibility and prevents Instruction Reordering.

  1. Reads and writes bypass CPU L1/L2 caches, writing directly to Main Memory.
  2. Establishes a Happens-Before Relationship.
  3. Does NOT guarantee Atomicity: Compound operations like count++ (read-modify-write) are NOT thread-safe under volatile alone.
Volatile Visibility Flag
public class FlagWorker implements Runnable {
    private volatile boolean running = true; // Visibility guaranteed across threads

    public void stop() { running = false; }

    @Override
    public void run() {
        while (running) { /* work */ }
    }
}
💡 Volatile ensures modifications to running are visible immediately across worker threads.
Key Takeaways
  • volatile guarantees main memory visibility and prevents instruction reordering.
  • Does NOT guarantee atomicity for compound updates (i++). Use AtomicInteger.
Knowledge Check

Is the operation count++ thread-safe if count is declared as volatile int count?

Q45: What is a Thread Deadlock and how can it be prevented?

A Deadlock occurs when two or more threads are blocked forever, each waiting for a lock held by the other.

  • 4 Coffman Conditions: Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait.
  • Prevention Strategies:
    1. Lock Ordering: Always acquire locks in a strict global sequence.
    2. Timed Locks: Use ReentrantLock.tryLock(timeout) to break waiting cycles.
Key Takeaways
  • Deadlocks require Circular Wait cycles across locks.
  • Prevent deadlocks using consistent Lock Ordering or tryLock(timeout).
Knowledge Check

Which strategy effectively prevents thread deadlocks in complex multi-lock systems?

Q46: How does ExecutorService manage Thread Pools, and what are the standard pool implementations?

ExecutorService decouples task submission from thread management.

  • FixedThreadPool: Fixed number of reusable threads backed by an unbounded LinkedBlockingQueue.
  • CachedThreadPool: Creates new threads dynamically as needed; reclaims idle threads after 60s. Backed by SynchronousQueue.
  • SingleThreadExecutor: Sequential single-worker execution.
  • ScheduledThreadPool: Executes tasks periodically or after delays.
Key Takeaways
  • FixedThreadPool uses an unbounded task queue (risk of OOM if overwhelmed). CachedThreadPool creates threads dynamically (risk of high thread counts).
Knowledge Check

What memory risk is associated with default Executors.newFixedThreadPool(10) under heavy load?

Q47: How do you tune custom ThreadPoolExecutor parameters?

Constructor signature: ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler)

  • Execution Flow:
    1. If active threads < corePoolSize, create new thread.
    2. If active threads $ge$ corePoolSize, queue task in workQueue.
    3. If workQueue is full AND active threads < maximumPoolSize, create new thread.
    4. If workQueue is full AND active threads = maximumPoolSize, trigger RejectedExecutionHandler (AbortPolicy, CallerRunsPolicy).
Key Takeaways
  • Tasks land in workQueue BEFORE worker count expands from corePoolSize to maximumPoolSize.
Knowledge Check

When does ThreadPoolExecutor begin spawning threads beyond corePoolSize up to maximumPoolSize?

Q48: How does ReentrantLock differ from the synchronized keyword?

FeaturesynchronizedReentrantLock
Lock MechanismImplicit JVM MonitorExplicit Java object API
FairnessUnfair lock acquisitionSupports Fair / Unfair lock configurations
InterruptibilityCannot interrupt waiting threadSupports lockInterruptibly()
Timed AcquisitionNot supportedSupports tryLock(timeout, unit)
Condition SupportSingle wait-set (wait/notify)Multiple condition variables (newCondition())
Key Takeaways
  • ReentrantLock provides advanced features (tryLock, fairness policies, multiple conditions).
Knowledge Check

Which feature is unique to ReentrantLock compared to synchronized blocks?

Q49: How does CompletableFuture enable non-blocking asynchronous pipeline chaining?

CompletableFuture<T> implements Future<T> and CompletionStage<T>. It allows chaining asynchronous tasks without blocking thread execution:

  • supplyAsync(): Executes task asynchronously on ForkJoinPool.commonPool().
  • thenApply(): Transforms result synchronously ($F: A o B$).
  • thenCompose(): Flattens nested futures ($F: A o ext{CompletableFuture}<B>$).
  • thenCombine(): Combines two independent futures in parallel.
  • exceptionally(): Non-blocking error recovery.
CompletableFuture Pipeline
CompletableFuture.supplyAsync(() -> fetchUserData(userId))
    .thenApply(user -> user.getEmail())
    .thenAccept(email -> sendNotification(email))
    .exceptionally(ex -> {
        logger.error("Pipeline error", ex);
        return null;
    });
💡 Executes background fetching, transformation, and processing without blocking main execution threads.
Key Takeaways
  • Enables functional non-blocking reactive pipelines.
  • thenCompose flattens nested futures; thenCombine executes futures in parallel.
Knowledge Check

Which CompletableFuture method is used to flatten a function that returns another CompletableFuture (similar to flatMap)?

Q50: How do Atomic variables (AtomicInteger) achieve lock-free thread safety using CAS?

Classes in java.util.concurrent.atomic (AtomicInteger, AtomicReference) provide thread-safe operations without locks using Compare-And-Swap (CAS) hardware instructions (CMPXCHG).

  • CAS Loop: Reads expected value $E$, computes new value $V$. Invokes atomic CAS CPU instruction. If memory location still matches $E$, updates to $V$. If another thread modified the value, CAS fails and loops to retry.
Key Takeaways
  • Lock-free thread safety using native CPU CAS instructions.
  • Eliminates thread context-switching overhead under low/moderate contention.
Knowledge Check

What low-level CPU instruction enables lock-free AtomicInteger operations?