title: Java StringBuilder and Thread Safety
body: <p>I am building up a String out of multiple pieces and want to use either <code>StringBuffer</code> or <code>StringBuilder</code> to do so. From the Java 5 docs, I see that <code>StringBuilder</code> is preferred when possible, with the caveat that</p>
  
  <blockquote>
    <p>Instances of <code>StringBuilder</code> are not safe for use by multiple threads.</p>
  </blockquote>
  
  <p>From this statement, I understand that I should not have a single <code>StringBuilder</code> instance shared by multiple threads. But what about this case:</p>
  
  <pre><code>//Is this safe?
  //foo() is called simultaneously by multiple threads
  String foo(String a, String b) {
      return new StringBuilder(a).append(b).toString();
  }
  </code></pre>
  
  <p>Here there could be multiple threads in the function at the same time, using the <code>StringBuilder</code> class at the same time (eg, concurrent access of static variables, if there are any), but each thread would have its own separate instance of <code>StringBuilder</code>. From the documentation, I can not quite decide whether this counts as use by multiple threads or not.</p>