🧠 What’s the Difference Between a Process and a Thread?
Feature | Process | Thread |
---|---|---|
Definition | A program in execution (independent) | A lightweight unit of execution within a process |
Memory | Has its own memory space | Shares memory with other threads in same process |
Isolation | Fully isolated from others | Not isolated — shares heap & static data |
Communication | Expensive (IPC: sockets, pipes) | Cheap (shared memory, synchronized access) |
Overhead | Heavy | Light |
Crash impact | Crash of one process doesn’t affect others | Crash of one thread can affect whole process |
Scheduling | Handled by OS | Also scheduled by OS (as lightweight processes) |
🔧 Real World Analogy
- A process is like a house — it has its own walls, kitchen, bathroom.
- A thread is like a person inside the house — multiple people (threads) can do things in parallel but share the same fridge, bathroom, etc.
📦 Java-Specific View
When you run a Java app:
java MyApp
- JVM creates 1 process: the Java process.
- You can create many threads using:
new Thread()
ExecutorService
ForkJoinPool
, etc.
All threads share the same heap (objects, static fields), but have their own call stacks (method frames, local variables).
🧪 Code Example
public class Demo {
public static void main(String[] args) {
new Thread(() -> System.out.println("Hello from thread")).start();
System.out.println("Hello from main thread");
}
}
Here:
- Both threads share the same process and memory
- They can access the same objects, but must synchronize to avoid conflicts
🔥 Summary
Topic | Thread | Process |
---|---|---|
Memory Sharing | ✅ Shares with others in process | ❌ Separate memory |
Communication Cost | 🟢 Low (shared mem) | 🔴 High (IPC) |
Overhead | 🟢 Low | 🔴 High |
Failure Isolation | ❌ Shared fate | ✅ Isolated |
Use in Java | Built-in (Thread , Executors) | Managed via ProcessBuilder |