🧠 Stack vs Heap in Multithreading
| Feature | Stack | Heap |
|---|---|---|
| 📌 Scope | Thread-local (private per thread) | Shared among all threads |
| 🧵 Thread-safety | ✅ Safe — each thread has its own stack | ❌ Not safe — needs synchronization |
| 🧠 Use | Stores local variables, method calls | Stores objects, instance data |
| ♻️ Lifetime | Lives while method is running | Lives until GC collects it |
| 🧹 Clean-up | Automatic when method returns | Garbage Collected |
🔍 Stack (Per Thread)
Each thread has its own stack where it stores:
- Method call frames
- Local variables (primitives and references)
- Return addresses
No two threads share the same stack, so: ✔️ No synchronization needed ✔️ Very fast access
🔍 Heap (Shared Across Threads)
The heap is where:
- All objects (
new SomeClass()) live - Instance variables of objects are stored
❗ Multiple threads can access the same object, so:
- You must use synchronization (
synchronized,ReentrantLock,volatile, etc.) - Otherwise, you’ll face race conditions or visibility issues
🔧 Example
public class Example {
private int shared = 0; // Lives in the heap
public void run() {
int local = 0; // Lives in the stack (per thread)
local++; // Thread-safe
shared++; // Not thread-safe!
}
}
🛡️ Thread Safety Summary
| Variable Type | Lives In | Thread-Safe? |
|---|---|---|
| Local variable | Stack | ✅ Yes (per-thread) |
| Object instance var | Heap | ❌ No (needs sync) |
| Static shared data | Heap | ❌ No (needs sync) |