I have a class SomeMutableData
with a public clone()
method. I want to make sure, that no thread ever sees an inconsistent state (assuming the instances will be passed around using the holder only). I assume using synchronization is the safest possibility, right?
public final class ThreadSafeHolder {
public ThreadSafeHolder(SomeMutableData data) {
storeData(data);
}
public synchronized SomeMutableData cloneData() {
return data.clone();
}
public synchronized void storeData(SomeMutableData data) {
this.data = data.clone();
}
private SomeMutableData data;
}
Is the following as safe as the first approach?
public final class ThreadSafeHolder2 {
public ThreadSafeHolder2(SomeMutableData data) {
storeData(data);
}
public SomeMutableData cloneData() {
return data.get().clone();
}
public void storeData(SomeMutableData data) {
this.data.set(data.clone());
}
private final AtomicReference<SomeMutableData> data
= new AtomicReference<SomeMutableData>();
}