title: Instance-controlled classes and multithreading
body: <p>In <em>Effective Java</em> Chapter 2, Item 1 Bloch suggests to consider static factory methods instead of constructors to initalize an object. On of the benefits he mentions is that this pattern allows classes to return the same object from repeated invocations:</p>
  
  <blockquote>
    <p>The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be <em>instance-controlled</em>. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b.</p>
  </blockquote>
  
  <p>How would this pattern work in a multi threaded environment? For example, I have an immutable class that should be instance-controlled because only one entity with the given ID can exist at a time:</p>
  
  <pre><code>public class Entity {
  
      private final UUID entityId;
  
      private static final Map&lt;UUID, Entity&gt; entities = new HashMap&lt;UUID, Entity&gt;();
  
      private Entity(UUID entityId) {
          this.entityId = entityId;
      }
  
      public static Entity newInstance(UUID entityId) {
          Entity entity = entities.get(entityId);
          if (entity == null) {
              entity = new Entity(entityId);
              entities.put(entityId, entity);
          }
          return entity;
      }
  
  }
  </code></pre>
  
  <p>What would happen if I call <code>newInstance()</code> from separated threads? How can I make this class thread-safe?</p>