Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: is 'Three Stooges' example really immutable?
    text
    copied!<p>In <code>Java Concurrency In Practice</code>, the following example is given to illustrate how to create an immutable class:</p> <p><a href="http://www.javaconcurrencyinpractice.com/listings/ThreeStooges.java" rel="nofollow">http://www.javaconcurrencyinpractice.com/listings/ThreeStooges.java</a></p> <p>This class has: <code>private final Set&lt;String&gt; stooges = new HashSet&lt;String&gt;();</code> which is initialized in its Constructor:</p> <pre><code>public ThreeStooges() { stooges.add("Moe"); stooges.add("Larry"); stooges.add("Curly"); } </code></pre> <p>and has a method</p> <pre><code>public boolean isStooge(String name) { return stooges.contains(name); } </code></pre> <p>to see if a name is one of the three stooges.</p> <p>But when I do this: <code>ThreeStooges ts = new ThreeStooges()</code>, is it guaranteed that the object will be properly constructed (i.e. the state of <code>stooges</code> correctly initialized) before its reference is set into <code>ts</code>?</p> <p>In other words, if I publish this object, is it possible that some thread will see it as incorrectly initialized (i.e. it will see <code>stooges</code> as empty when accessed through <code>isStooge()</code>)? </p> <p>My understanding is that an immutable object will be properly constructed and correctly visible when it's published - (because it uses final instance variables). Is my understanding correct? If yes, is this class still immutable?</p> <p>EDIT: it seems from the comments I saw that it's difficult to believe an object can be seen by other threads before its Constructor completes. Here's a link on that: <a href="http://jeremymanson.blogspot.in/2008/05/double-checked-locking.html" rel="nofollow">http://jeremymanson.blogspot.in/2008/05/double-checked-locking.html</a></p>
 

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