Skip to content
Advertisement

Visibility of mutable object under different locks in Java

mFeaute is a mutable object.

I want to know if the change of mFeature in setFeature(Feature feature) is visible to mFeature in useFeature(…) with a different explicit form of synchronized.

Thanks.

public class FeatureService {
    private static Feature mFeature= null; 
    private final Object MUTEX = new Object();
    ...

    static void setFeature(Feature feature){
        // doSomething
        synchronized (FeatureService.class){
            mFeature = feature;
            // doSomething
        }
        // doSomething
    }

    public void useFeature(...){
        // doSomething
        synchronized (MUTEX){
            someFunction(mFeature);
            // doSomething 
        }
        // doSomething
    }
}
}

Advertisement

Answer

The above code is suffering from a data race and hence is broken. You do not have a happens before edge between the write and the read of mfeature because different locks are used. You need to use the same lock instance for both reading and writing.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement