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 ?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
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.