Java Concurrency Basics - Interview Questions & Answers
Master Java Concurrency Basics with interview-focused questions and answers. Learn Process, Thread, Multithreading, Thread Lifecycle, Runnable, and Synchronization fundamentals with real Java examples.
Java Concurrency Basics - Interview Questions & Answers
Introduction
Modern enterprise applications must handle thousands of requests simultaneously.
Imagine an online banking system where users are:
- Logging in
- Checking account balances
- Making payments
- Transferring money
- Downloading statements
If every request waits for the previous one to finish, the application becomes slow and unresponsive.
Java Concurrency enables multiple tasks to execute efficiently, improving application throughput and responsiveness.
Why Interviewers Ask About Concurrency?
Concurrency is one of the most important topics for:
- Java Developer
- Senior Java Developer
- Spring Boot Developer
- Solution Architect
Interviewers expect developers to understand:
- Threads
- Processes
- Thread Lifecycle
- Runnable
- Synchronization
- Race Conditions
- Thread Safety
flowchart TD
Application --> MultipleThreads
MultipleThreads --> Request1
MultipleThreads --> Request2
MultipleThreads --> Request3
MultipleThreads --> Request4
Interview Question 1
What is Concurrency?
Answer
Concurrency is the ability of an application to execute multiple tasks during the same period of time.
It does not necessarily mean tasks execute at the exact same instant. Instead, tasks make progress by sharing CPU time or running simultaneously on multiple CPU cores.
Concurrency improves:
- Throughput
- Resource Utilization
- User Experience
- Scalability
Diagram
flowchart LR
Application --> Task1
Application --> Task2
Application --> Task3
Task1 --> CPU
Task2 --> CPU
Task3 --> CPU
Java Example
Runnable task = () ->
System.out.println(
Thread.currentThread().getName()
);
new Thread(task).start();
new Thread(task).start();
Production Example
A Spring Boot application processes:
- REST API Requests
- Kafka Messages
- Database Queries
- Notification Services
at the same time.
Interview Tip
Remember:
Concurrency improves responsiveness.
It does not always mean multiple CPUs are executing tasks simultaneously.
Interview Question 2
What is the difference between Process and Thread?
Answer
A Process is an independent running program.
A Thread is a lightweight execution unit inside a process.
A process may contain multiple threads.
Comparison
| Process | Thread |
|---|---|
| Independent Program | Small execution unit |
| Own Memory | Shares Process Memory |
| Heavyweight | Lightweight |
| Expensive Creation | Fast Creation |
| Higher Context Switching | Lower Context Switching |
Diagram
flowchart TD
OperatingSystem --> JavaProcess
JavaProcess --> Thread1
JavaProcess --> Thread2
JavaProcess --> Thread3
Java Example
public class ProcessVsThread {
public static void main(String[] args) {
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start();
t2.start();
}
}
Production Example
A Spring Boot application runs as one Java process.
Inside that process:
- HTTP Request Threads
- Kafka Consumer Threads
- Scheduler Threads
- Background Worker Threads
run concurrently.
Interview Tip
A process owns resources.
Threads share those resources.
Interview Question 3
What is Multithreading?
Answer
Multithreading means executing multiple threads within a single process.
Advantages:
- Better CPU utilization
- Faster processing
- Improved responsiveness
- Higher throughput
- Efficient resource sharing
Diagram
flowchart TD
JavaApplication --> MainThread
MainThread --> Worker1
MainThread --> Worker2
MainThread --> Worker3
Java Example
public class Worker extends Thread {
@Override
public void run() {
System.out.println(
Thread.currentThread().getName()
);
}
public static void main(String[] args) {
new Worker().start();
new Worker().start();
}
}
Production Example
Online Banking
Different threads handle:
- Login
- Balance Inquiry
- Fund Transfer
- Transaction History
simultaneously.
Interview Tip
Every Java application starts with one thread called the Main Thread.
Interview Question 4
What is the Thread Lifecycle?
Answer
A Java thread passes through multiple states during its execution.
Thread Lifecycle
flowchart LR
NEW --> RUNNABLE --> RUNNING
RUNNING --> WAITING
WAITING --> RUNNABLE
RUNNING --> BLOCKED
BLOCKED --> RUNNABLE
RUNNING --> TERMINATED
Thread States
| State | Description |
|---|---|
| NEW | Thread created |
| RUNNABLE | Ready to execute |
| RUNNING | Currently executing |
| WAITING | Waiting indefinitely |
| BLOCKED | Waiting for monitor lock |
| TIMED_WAITING | Waiting for specified time |
| TERMINATED | Execution completed |
Java Example
Thread thread = new Thread(() -> {
System.out.println("Running");
});
System.out.println(thread.getState());
thread.start();
Interview Tip
Many interviewers ask:
Explain every thread state with examples.
Practice drawing the lifecycle diagram.
Interview Question 5
What is the difference between extending Thread and implementing Runnable?
Answer
Java provides two ways to create threads.
Option 1
Extend Thread
class Worker extends Thread {
@Override
public void run() {
System.out.println("Thread");
}
}
Option 2
Implement Runnable
class Worker implements Runnable {
@Override
public void run() {
System.out.println("Runnable");
}
}
Comparison
| Thread | Runnable |
|---|---|
| Extends Thread class | Implements Runnable interface |
| Cannot extend another class | Can extend another class |
| Less Flexible | More Flexible |
| Tightly Coupled | Better Design |
Diagram
flowchart TD
CreateThread --> ExtendThread
CreateThread --> ImplementRunnable
ImplementRunnable --> ThreadObject
ThreadObject --> start()
Production Recommendation
Most enterprise applications use:
- Runnable
- Callable
- ExecutorService
instead of extending Thread directly.
Interview Tip
Prefer Runnable because Java supports only single inheritance.
Interview Question 6
What is Synchronization?
Answer
Synchronization is a mechanism that ensures only one thread can access a shared resource at a time.
It prevents:
- Race Conditions
- Data Corruption
- Inconsistent Results
Synchronization is required whenever multiple threads modify shared data.
Diagram
flowchart LR
Thread1 --> Lock
Lock --> SharedResource
Thread2 --> Lock
Thread3 --> Lock
Java Example
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
Production Example
Bank Account
Multiple users attempt to withdraw money simultaneously.
Synchronization ensures only one withdrawal updates the balance at a time.
Interview Tip
Synchronization improves correctness but excessive synchronization can reduce application performance.
Interview Question 7
What is a Race Condition?
Answer
A Race Condition occurs when multiple threads access and modify shared data simultaneously, causing unpredictable results.
Diagram
sequenceDiagram
participant Thread1
participant Counter
participant Thread2
Thread1->>Counter: Read Value = 100
Thread2->>Counter: Read Value = 100
Thread1->>Counter: Write 101
Thread2->>Counter: Write 101
Note over Counter: Expected = 102<br/>Actual = 101
Java Example
class Counter {
int count = 0;
public void increment() {
count++;
}
}
Multiple threads calling increment() may produce incorrect results.
Solution
public synchronized void increment() {
count++;
}
Interview Tip
Race conditions usually occur because the operation:
count++;
is not atomic.
It internally performs:
- Read
- Increment
- Write
Interview Question 8
What is Thread Safety?
Answer
A class is Thread Safe if multiple threads can use it simultaneously without causing incorrect behavior.
Thread Safe Examples
- ConcurrentHashMap
- AtomicInteger
- String
- Local Variables
Not Thread Safe
- HashMap
- ArrayList
- LinkedList
- HashSet
Diagram
flowchart LR
MultipleThreads --> ThreadSafeClass
ThreadSafeClass --> CorrectResults
Java Example
Map<Integer, String> users =
new ConcurrentHashMap<>();
users.put(1, "Java");
Interview Tip
Thread safety is achieved using:
- Synchronization
- Locks
- Atomic Classes
- Concurrent Collections
Interview Question 9
What is Context Switching?
Answer
A CPU executes one thread at a time on a single core.
When multiple threads compete for CPU time, the operating system switches between them.
This is called Context Switching.
Diagram
flowchart LR
CPU --> Thread1
CPU --> Thread2
CPU --> Thread3
CPU --> Thread4
Advantages
- Better responsiveness
- Efficient CPU utilization
Disadvantages
- CPU overhead
- Increased latency
- Memory overhead
Production Example
Spring Boot Server
1000 incoming requests
ā
Only a limited number of worker threads execute at any moment.
The operating system continuously switches between them.
Interview Tip
Too many threads cause excessive context switching and can reduce application performance.
Interview Question 10
What is a Daemon Thread?
Answer
A Daemon Thread is a background thread that supports user threads.
It automatically terminates when all user threads finish.
Examples
- Garbage Collector
- JVM Cleanup Threads
- Background Monitoring
Diagram
flowchart TD
MainThread --> WorkerThread
MainThread --> DaemonThread
WorkerThread --> ApplicationExit
ApplicationExit --> DaemonStops
Java Example
Thread monitor = new Thread(() -> {
while(true){
System.out.println("Monitoring...");
}
});
monitor.setDaemon(true);
monitor.start();
Interview Tip
A JVM exits when all user threads finish, even if daemon threads are still running.
Common Interview Mistakes
- Confusing concurrency with parallelism.
- Assuming every multithreaded application is thread-safe.
- Using
HashMapin concurrent applications. - Forgetting synchronization for shared mutable data.
- Creating too many threads manually.
- Extending
Threadinstead of usingExecutorService. - Ignoring race conditions.
- Believing
volatilealone provides thread safety. - Not understanding thread lifecycle states.
Quick Revision Cheat Sheet
| Concept | Key Point |
|---|---|
| Concurrency | Multiple tasks make progress together |
| Process | Independent running program |
| Thread | Lightweight execution unit |
| Multithreading | Multiple threads inside one process |
| Synchronization | Protects shared resources |
| Race Condition | Multiple threads modify shared data simultaneously |
| Thread Safety | Safe concurrent access |
| Context Switching | CPU switches between threads |
| Daemon Thread | Background JVM thread |
| Best Practice | Use ExecutorService instead of creating threads manually |
Interviewer's Expectations
Junior Java Developer
- Understand processes and threads.
- Explain concurrency basics.
- Know the thread lifecycle.
- Differentiate Thread and Runnable.
Senior Java Developer
- Explain synchronization.
- Identify race conditions.
- Discuss thread safety.
- Recommend concurrent collections.
- Understand JVM thread behavior.
Solution Architect
- Design scalable concurrent systems.
- Minimize thread contention.
- Select appropriate concurrency utilities.
- Optimize throughput and latency.
- Balance synchronization with performance.
Related Interview Questions
- ExecutorService
- Future vs CompletableFuture
- ForkJoinPool
- Locks
- Atomic Classes
- Concurrent Collections
- CountDownLatch
- CyclicBarrier
- Semaphore
- Java Memory Model (JMM)
- Volatile vs synchronized
- Thread Pools
Summary
Concurrency is the foundation of modern Java enterprise applications. Every web server, Spring Boot application, Kafka consumer, scheduler, and microservice relies on multiple threads to process work efficiently. Understanding concepts such as threads, synchronization, race conditions, thread safety, context switching, and daemon threads is essential for writing reliable and scalable applications.
For interviews, don't just define these concepts. Explain why synchronization is needed, how race conditions occur, when to use thread-safe collections, and how concurrency impacts real production systems. Relating your answers to practical scenarios such as banking transactions, REST API processing, and background job execution demonstrates the production-level expertise expected from senior Java developers and solution architects.