Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can one break this (non?) thread safe object?
    text
    copied!<p>I replied to a <a href="https://stackoverflow.com/questions/9621260/thread-safety-of-a-fluent-like-class-using-clone-and-non-final-fields/9621337#9621337">question</a> earlier about thread safety which did not get a definite answer (I think).</p> <p>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!</p> <p>I understand the risk of reordering but I don't see how it could apply in that case, in the sense that the <code>clone</code> instance in the <code>bar()</code> method is local and the change on its fields is done before being released to the outside world with <code>return</code>, after which the instance is effectively immutable. So a thread looking at the returned object would see it with its <code>bar</code> field already set to the correct value...</p> <p><strong>So my question is:</strong> <s>what kind of code</s> Could you show a piece of code that uses <code>IsItSafe</code> and that could lead 2 threads to see different values of the <code>bar</code> field of a given instance of <code>IsItSafe</code>?</p> <p>For reference and ease of reading I copy the code here:</p> <pre><code>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); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload