Java.Multithreading.What is the difference between stack and heap in terms of multithreading?

🧠 Stack vs Heap in Multithreading

FeatureStackHeap
📌 ScopeThread-local (private per thread)Shared among all threads
🧵 Thread-safety✅ Safe — each thread has its own stack❌ Not safe — needs synchronization
🧠 UseStores local variables, method callsStores objects, instance data
♻️ LifetimeLives while method is runningLives until GC collects it
🧹 Clean-upAutomatic when method returnsGarbage 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 TypeLives InThread-Safe?
Local variableStack✅ Yes (per-thread)
Object instance varHeap❌ No (needs sync)
Static shared dataHeap❌ No (needs sync)
This entry was posted in Без рубрики. Bookmark the permalink.