Why are local variables thread safe in Java

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.

Leave a Comment