Java Interview Preparation

Multithreading Interview Questions

Threads, executors, synchronization, locks, concurrency utilities, and virtual threads.

Multithreading Interview Focus

Threads, executors, synchronization, locks, concurrency utilities, and virtual threads.

Multithreading interview questions

Interview questions

20 matching

1. What is multithreading in Java? Beginner

Multithreading is the execution of multiple threads concurrently inside one process. A thread is a lightweight unit of execution with its own stack and program counter, while threads in the same process share heap objects and other resources. An application may use different threads for requests, database work, notifications, logging, and background tasks. The JVM and operating system decide the execution order, so code must not depend on a particular order unless it explicitly coordinates the threads.

2. What is the difference between a process and a thread? Beginner

A process is an independent running program with its own memory space and operating-system resources. A thread is an execution path inside a process. Threads are cheaper to create and communicate through shared heap objects, but a thread failure can affect the whole process. Each thread has its own stack and program counter, while threads share the process heap, static data, and open resources. Processes provide stronger isolation; threads provide lightweight concurrency within that isolation.

3. What are the advantages of multithreading? Beginner

Multithreading can keep an application responsive while background work runs, improve throughput on multi-core CPUs, and allow other tasks to progress while one thread waits for I/O. It is useful for handling multiple requests, processing files, and running independent jobs. The trade-off is added complexity: shared mutable state can cause race conditions, deadlocks, starvation, visibility bugs, and difficult-to-reproduce failures. Use concurrency when the workload benefits from it and prefer high-level concurrency utilities where possible.

4. What are the different ways to create a thread in Java? Beginner

You can extend Thread, implement Runnable, use a Runnable lambda, submit Runnable or Callable tasks to ExecutorService, or create asynchronous stages with CompletableFuture. Extending Thread couples the task to a thread object. Runnable represents work without a result, while Callable can return a result and throw checked exceptions. In production code, submitting tasks to a properly sized executor is usually better than creating an unlimited number of raw Thread objects.

5. What is the difference between extending Thread and implementing Runnable? Beginner

Extending Thread makes the class both the task and the thread, so it cannot extend another class and is harder to reuse. Implementing Runnable separates the work from the execution mechanism. The same Runnable can run in a Thread, an ExecutorService, or a scheduled executor, and the task class can still extend another class. Therefore, implementing Runnable or using a Callable is generally preferred unless a custom Thread type is specifically required.

6. What is the lifecycle of a thread in Java? Intermediate

Thread.State defines NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. NEW means start() has not been called. RUNNABLE means the thread is ready or running. BLOCKED means it is waiting for an intrinsic lock. WAITING means it waits indefinitely for another action, such as notify or join. TIMED_WAITING means it waits for a duration, such as sleep. TERMINATED means run() has completed. A terminated Thread cannot be started again.

7. What is the difference between the start() and run() methods? Beginner

start() asks the JVM to create and schedule a new thread, which then invokes run(). Calling run() directly is only a normal method call and executes on the current thread. Therefore, start() provides concurrent execution, while run() does not create another execution path. A Thread can be started only once; calling start() a second time throws IllegalThreadStateException. Directly calling run() is appropriate only when synchronous execution is intentional.

8. What is the difference between sleep(), wait() and join()? Intermediate

sleep() is a static Thread method that pauses the current thread for a duration and does not release monitors it holds. wait() is an Object method that must be called while owning that object’s monitor; it releases that monitor and waits for notification, interruption, or timeout. join() makes the current thread wait until another thread finishes. InterruptedException should normally be handled by restoring the interrupt flag with Thread.currentThread().interrupt().

9. What is thread synchronization, and why is it required? Intermediate

Synchronization coordinates access to shared mutable state. It provides mutual exclusion so only one thread enters a protected critical section at a time and establishes visibility between threads that use the same lock. For example, count++ is a read, modify, and write sequence, so two threads can lose an update without protection. Use synchronized blocks or methods, locks, atomic classes, concurrent collections, immutability, or thread confinement based on the problem.

10. What is the difference between a synchronized method and a synchronized block? Intermediate

A synchronized instance method locks this for its complete body, while a synchronized static method locks the Class object. A synchronized block protects only the selected code and can use a private lock object. Blocks are more flexible and can keep the critical section shorter, which often improves concurrency. Avoid locking on publicly accessible objects because unrelated code can accidentally acquire the same lock. Use a method when the whole method is the critical section and a block when only part needs protection.

11. What is a race condition? Intermediate

A race condition occurs when the result depends on the unpredictable timing of threads accessing shared mutable data. A common example is two threads checking a bank balance and then withdrawing money before either update is visible to the other. Compound operations such as count++, check-then-act logic, and containsKey followed by put are vulnerable. Prevent races with synchronized sections, locks, atomic operations, concurrent collections, immutability, or thread confinement.

12. What is a deadlock, and how can it be prevented? Advanced

A deadlock occurs when threads wait forever for locks held by one another. For example, Thread A holds lock A and waits for lock B while Thread B holds lock B and waits for lock A. Prevent it by acquiring multiple locks in one consistent global order, avoiding unnecessary nested locks, keeping critical sections short, avoiding external calls while locked, and using tryLock with a timeout where appropriate. Thread dumps can help confirm a deadlock in production.

13. What is the difference between deadlock, livelock and starvation? Advanced

Deadlock means threads are blocked forever in a circular wait. Livelock means threads remain active and keep reacting or retrying but make no useful progress. Starvation means one thread repeatedly fails to obtain CPU time, a lock, or another resource while other threads continue. Reduce these problems with consistent lock ordering, bounded retries with backoff, fair locks when justified, short critical sections, suitable pool sizes, and separation of long-running tasks.

14. What is the purpose of the volatile keyword? Intermediate

volatile guarantees visibility of a variable between threads and provides ordering rules around its reads and writes. It is useful for a stop flag, status value, or safely published reference when each operation is independent. It does not make compound operations atomic. For example, volatile int count does not make count++ safe because increment still reads, changes, and writes the value. Use synchronization or an atomic class when an update depends on the previous value or several fields must remain consistent.

15. What is the difference between volatile and synchronized? Advanced

volatile provides visibility and ordering for a single variable but does not lock or make compound operations atomic. synchronized provides visibility, mutual exclusion, and atomicity for the protected critical section. Use volatile for an independent state flag such as running. Use synchronized when a read-modify-write operation is required, multiple fields form one invariant, or only one thread may execute a section at a time. Atomic classes are another option for individual lock-free updates.

16. What are atomic classes in Java? Intermediate

Atomic classes in java.util.concurrent.atomic provide thread-safe operations on individual values without explicit synchronized blocks. Examples include AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference, LongAdder, and LongAccumulator. Methods such as incrementAndGet and compareAndSet use atomic read-modify-write operations. LongAdder can improve throughput for highly contended counters. Atomic classes are not enough when several variables must be changed together as one transaction; that situation needs a lock or another coordination design.

17. What is the Executor Framework? Intermediate

The Executor Framework is a high-level API for submitting tasks without manually managing every thread. ExecutorService manages worker threads, queues, task execution, Future results, and shutdown. ScheduledExecutorService supports delayed and periodic tasks, while ThreadPoolExecutor gives precise control over pool size, queue capacity, keep-alive time, thread creation, and rejection policy. Always shut down executors that the application owns and choose bounded resources for production workloads.

18. What is the difference between Runnable and Callable? Intermediate

Runnable represents a task whose run() method returns no value and cannot declare checked exceptions. Callable represents a task whose call() method returns a value and can throw checked exceptions. Both can be submitted to an ExecutorService, but Callable commonly produces a Future result. Use Runnable for fire-and-forget work and Callable when the caller needs a result or needs the task to report a checked failure.

19. What is the difference between Future and CompletableFuture? Advanced

Future represents a result that may be available later and commonly requires blocking get(). CompletableFuture supports callback-style stages such as thenApply, thenCompose, thenCombine, allOf, and exceptionally. It can chain asynchronous operations, combine independent results, and handle failures without manually blocking at every step. Both can still be misused: blocking inside an asynchronous stage or using an unsuitable executor can exhaust threads and remove the expected performance benefit.

20. What is a thread pool, and what are the different types of thread pools available in Java? Intermediate

A thread pool is a managed group of reusable worker threads. Tasks wait in a queue and are executed by available workers, avoiding the memory and scheduling cost of creating a thread for every task. Common choices are fixed pools for bounded concurrency, single-thread executors for ordered work, scheduled pools for delayed or periodic jobs, work-stealing pools for parallel tasks, and custom ThreadPoolExecutor instances for explicit queue and rejection policies. Pool size should be measured against CPU, I/O, queue growth, and downstream capacity.

How to Prepare for Java Technical Interviews

Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.

Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.

Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.