Java Multithreading – Conceptually What Does It Mean When Each Thread Gets Its Own Stack?

concurrencyjavamultithreadingstack

I have been reading Java Concurrency in Practice by Brian Goetz and inside the section Stack Confinement it is mentioned that each thread gets its own stack and so local variables are intrinsically confined to the executing thread; they exist on the executing threads stack, which is not accessible to other threads. What does he mean that each thread has its own execution stack ?

Best Answer

You know when you break to the debugger for whatever reason, and the IDE gives you a stack trace? And each method (stack frame) has its own set of local variables that you can examine in the debugger?

That's the "execution stack" of your program. It shows what the local state of your program looks like at the moment. What the author is saying is that each thread gets its own distinct execution stack like that. It has its own call stack, and each of the methods have their own local variables.

Because the variables are stored as part of the execution stack and not in the heap, they are unique to the thread that's being run and can't be shared directly. You can copy them, or pass references to objects to other threads in various ways, though, so that's mostly an academic distinction.

Related Topic