title: Thread safety of enum valueOf()
body: <p>This is a variation of the perpertual <strong>"lengthy-if or switch"</strong> dilemma...</p>
  
  <p>Consider a multithreaded application using a static method that contains a long (over a dozen conditions) <code>if</code> statement, which checks the type of an object and returns a value accordingly, i.e. something like</p>
  
  <pre><code>public static String checkType(Class&lt;?&gt; type)
  {
      if (type == A.class)
      {
          return aString;
      }
      else if (type == B.class)
      {
          return bString;
      }
      ...
      else if (type == z.class)
      {
          return zString;
      }
  }
  </code></pre>
  
  <p>Obviously a switch statement is not directly applicable here, so a common pattern is to have an <code>enum</code> and call its <code>valueOf()</code>, i.e. do something like</p>
  
  <pre><code>public enum Strings
  {
      A(aString), B(bString), ..., Z(zString)
  
      private final String value;
  
      private Strings(String value)
      {
          this.value = value;
      }
  
      public String value()
      {
          return this.value;
      }
  }
  </code></pre>
  
  <p>So, <code>checkType()</code> could be re-written as</p>
  
  <pre><code>public static String checkType(Class&lt;?&gt; type)
  {
      return Strings.valueOf(getActualTypeName(type.getClass().getName())).value();
  }
  </code></pre>
  
  <p>with appropriate checks for <code>null</code> values added in production code and some String processing for non-primitive types, inside the <code>getActualTypeName()</code> method, to retrieve the actual type name from strings like <code>"class java.lang.Long"</code> (for primitives, the <code>getName()</code> method returns the expected string, e.g. "<code>long"</code>).</p>
  
  <p>However, if <code>valueOf()</code> is not thread-safe, this will not work in a concurrent environment. The same applies to using a (normal) <code>Map</code> object and probably these two alternatives are variants of the same pattern, since <code>enum.valueOf()</code> is apparently based on</p>
  
  <pre><code>Enum.valueOf(Class&lt;T&gt; enumType, String name)
  </code></pre>
  
  <p>which calls</p>
  
  <pre><code>enumType.enumConstantDirectory().get(name);
  </code></pre>
  
  <p>in the <code>Class.java</code> class.</p>
  
  <p>The <code>enumConstantDirectory()</code> method, every time invoked, returns a new <code>HashMap</code>, created from a copy of the <code>values()</code> array.</p>
  
  <p>Would that be thread safe?</p>