I replied to a question earlier about thread safety which did not get a definite answer (I think).
So I have been trying to convince myself that the design is broken (visibility) by having thousands of threads read and write that object - but I have not been able to get anything unexpected. That is obviously not a proof that it is thread safe, probably merely a proof of my own limitations!
I understand the risk of reordering but I don't see how it could apply in that case, in the sense that the clone
instance in the bar()
method is local and the change on its fields is done before being released to the outside world with return
, after which the instance is effectively immutable. So a thread looking at the returned object would see it with its bar
field already set to the correct value...
So my question is: what kind of code Could you show a piece of code that uses IsItSafe
and that could lead 2 threads to see different values of the bar
field of a given instance of IsItSafe
?
For reference and ease of reading I copy the code here:
public class IsItSafe implements Cloneable {
private int foo;
private int bar;
public IsItSafe foo(int foo) {
IsItSafe clone = clone();
clone.foo = foo;
return clone;
}
public IsItSafe bar(int bar) {
IsItSafe clone = clone();
clone.bar = bar;
return clone;
}
public int getFoo() {
return foo;
}
public int getBar() {
return bar;
}
protected IsItSafe clone() {
try {
return (IsItSafe) super.clone();
} catch (CloneNotSupportedException e) {
throw new Error(e);
}
}
}