Why are local variables thread safe in Java

Anand picture Anand · Oct 10, 2012 · Viewed 46.1k times · Source

I was reading multi-threading in Java and I come across this

Local variables are thread safe in Java.

Since then I have been thinking How/Why local variables are thread safe.

Can somebody please let me know.

Answer

kosa picture kosa · Oct 10, 2012

When you create a thread it will have its own stack created. Two threads will have two stacks and one thread never shares its stack with other thread.

All local variables defined in your program will be allocated memory in stack (As Jatin commented, memory here means, reference-value for objects and value for primitive types) (Each method call by a thread creates a stack frame on its own stack). As soon as method execution is completed by this thread, stack frame will be removed.

There is great lecture by Stanford professor in youtube which may help you in understanding this concept.