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.
Advertisement
Answer
When you create a thread it will have its own call 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.