Why are local variables thread safe in Java

Solution 1:

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.

Solution 2:

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.

public void someMethod(){

   long threadSafeInt = 0;

   threadSafeInt++;
}

Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads

Solution 3:

Think of methods like definitions of functionality. When two threads run the same method, they are in no way way related. They will each create their own version of each local variable, and will be unable to interact with each other in any way.

If variables aren't local (like instance variables defined outside of a method at the class level), then they are attached to the instance (not to a single run of the method). In this case, two threads running the same method both see the one variable, and this isn't thread-safe.

Consider these two cases:

public class NotThreadsafe {
    int x = 0;
    public int incrementX() {
        x++;
        return x;
    }
}

public class Threadsafe {
    public int getTwoTimesTwo() {
        int x = 1;
        x++;
        return x*x;
    }
}

In the first, two threads running on the same instance of NotThreadsafe will see the same x. This could be dangerous, because the threads are trying to change x! In the second, two threads running on the same instance of Threadsafe will see totally different variables, and can't affect each other.