title: Synchronizing access to SimpleDateFormat
body: <p>The javadoc for SimpleDateFormat states that SimpleDateFormat is not synchronized.</p>
  
  <blockquote>
    <p>"Date formats are not synchronized. It
    is recommended to create separate
    format instances for each thread. If
    multiple threads access a format
    concurrently, it must be synchronized
    externally."</p>
  </blockquote>
  
  <p>But what is the best approach to using an instance of SimpleDateFormat in a multi threaded environment. Here are a few options I have thought of, I have used options 1 and 2 in the past but I am curious to know if there are any better alternatives or which of these options would offer the best performance and concurrency.</p>
  
  <p>Option 1: Create local instances when required</p>
  
  <pre><code>public String formatDate(Date d) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      return sdf.format(d);
  }
  </code></pre>
  
  <p>Option 2: Create an instance of SimpleDateFormat as a class variable but synchronize access to it.</p>
  
  <pre><code>private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  public String formatDate(Date d) {
      synchronized(sdf) {
          return sdf.format(d);
      }
  }
  </code></pre>
  
  <p>Option 3: Create a ThreadLocal to store a different instance of SimpleDateFormat for each thread.</p>
  
  <pre><code>private ThreadLocal&lt;SimpleDateFormat&gt; tl = new ThreadLocal&lt;SimpleDateFormat&gt;();
  public String formatDate(Date d) {
      SimpleDateFormat sdf = tl.get();
      if(sdf == null) {
          sdf = new SimpleDateFormat("yyyy-MM-hh");
          tl.set(sdf);
      }
      return sdf.format(d);
  }
  </code></pre>