Home > Back-end >  Visibility of mutable object under different locks in Java
Visibility of mutable object under different locks in Java

Time:10-28

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
    }
}
}

CodePudding user response:

It is unclear what you are trying to synchronize on (ClassA and ObjectB are vague). In general, you want to synchronize on a single mutex when interacting with a given shared resource. Create an Object to serve as the mutex upon which you synchronize when accessing the internal mFeature.

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

  static void setFeature(Feature feature){
    synchronized (MUTEX){
        mFeature = feature;
    }
  }

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

CodePudding user response:

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.

  • Related