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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.