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.
JavaScript
x
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.