title: Java concurrency in practice - safe publication, immutable object and volatile
body: <p>I'm reading &quot;Java concurrency in practice&quot; and one thing is confusing me.</p>
  <pre class="lang-java prettyprint-override"><code>class OneValueCache {
      private final BigInteger lastNumber;
      private final BigInteger[] lastFactors;
  
      public OneValueCache(BigInteger lastNumber, BigInteger[] lastFactors) {
          this.lastNumber = lastNumber;
          this.lastFactors = Arrays.copyOf(lastFactors, lastFactors.length);
      }
  
      public BigInteger[] getFactors(BigInteger i) {
          if (lastNumber == null || !lastNumber.equals(i)) {
              return null;
          }
          return Arrays.copyOf(lastFactors, lastFactors.length);
      }
  }
  
  class VolatileCachedFactorized implements Servlet {
      private volatile OneValueCache cache = new OneValueCache(null, null);
  
      public void service(ServletRequest req, ServletResponse resp) {
          BigInteger i = extractFromRequest(req);
          BigInteger[] factors = cache.getFactors(i);
  
          if (factors == null) {
              factors = factor(i);
              cache = new OneValueCache(i, factors);
          }
  
          encodeIntoResponse(resp, factors);
      }
  }
  </code></pre>
  <p>In above code author uses <code>volatile</code> with reference to immutable <code>OneValueCache</code>, but a few page later he writes:</p>
  <p><code>Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them.</code></p>
  <p>So .. <code>volatile</code> is not necessary in above code?</p>