Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you safely synchronize on a Java method parameter?

Tags:

People also ask

Can we synchronize method in Java?

Yes, we can synchronize a run() method in Java, but it is not required because this method has been executed by a single thread only.

Is synchronized method thread safe?

synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access.

Can you synchronize on variable Java?

You can have both static synchronized method and nonstatic synchronized method and synchronized blocks in Java but we can not have synchronized variable in java.

What is the disadvantage of synchronization in Java?

In simple two lines Disadvantage of synchronized methods in Java : Increase the waiting time of the thread. Create performance problem.


Take this code:

public class MyClass {
    private final Object _lock = new Object();
    private final MyMutableClass _mutableObject = new MyMutableClass()

    public void myMethod() {
        synchronized(_lock) { // we are synchronizing on instance variable _lock
            // do something with mutableVar 
            //(i.e. call a "set" method on _mutableObject)
        }
    }
}

now, imagine delegating the code inside myMethod() to some helper class where you pass the lock

public class HelperClass {
    public helperMethod(Object lockVar, MyMutableClass mutableVar) {
        synchronized(lockVar) { // we are now synchronizing on a method param, 
                                // each thread has own copy
            // do something with mutableVar 
            // (i.e. call a "set" method on mutableVar)
        }
    }
}

can "myMethod" be re-written to use the HelperClass by passing its lock var, so that everything is still thread safe? i.e.,

public void myMethod() {
    _helperObject.helperMethod(_lock, _mutableObject);
}

I am not sure about this, because Java will pass the lockVar by value, and every thread will get a separate copy of lockVar (even though each copy points to the same object on the heap). I guess the question comes down to how 'synchronized' keyword works -- does it lock on the variable, or the value on the heap that the variable references?