Is reasonable to synchronized on local variable?

NingLee :

From the java memory model, we know every thread has his own thread stack, and that local variables are placed in each thread's own thread stack.

And that other threads can't access these local variables.

So in which case, we should synchronized on local variables?

developer :

You are talking about the below case:

public class MyClass {
    public void myMethod() {
        //Assume Customer is a Class
        Customer customer = getMyCustomer();
        synchronized(customer) {
            //only one thread at a time can access customer object
              which ever holds the lock
        }
    }
}

In the above code, customer is a local reference variable, but you are still using a synchronized block to restrict access to the object customer is pointing to (by a single thread at a time).

In Java memory model, objects live in heap (even though references are local to a Thread which live in a stack) and synchronization is all about restricting access to an object on the heap by exactly one thread at a time.

In short, when you say local variable (non-primitive), only reference is local, but not the actual object itself i.e., it is actually referring to an object on the heap which can be accessed by many other threads. Because of this, you need synchronization on the object so that single thread can only access that object at a time.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447287&siteId=1