title: What is the best Scala thread-safe way to write to a BufferedWriter?
body: <p>I have a simple method that writes a line of data to a File followed by a new line that is executed asynchronously.</p>
  <pre><code>  def writeToFile(bw: BufferedWriter, str: String) = {
      bw.write(str)
      bw.newLine
    }
  </code></pre>
  <p>When my program runs I'm getting &quot;mixed up&quot; rows in the file due to the async nature of the calls.  For instance...say writeToFile(bw, &quot;foo&quot;) is executed 3 times asynchronously I may get:</p>
  <p><strong>correct output</strong></p>
  <blockquote>
  <p>foo</p>
  <p>foo</p>
  <p>foo</p>
  </blockquote>
  <p><strong>possible incorrect output</strong></p>
  <blockquote>
  <p>foofoo</p>
  <p>foo</p>
  </blockquote>
  <p>I'm able to avoid this possibility by using <em>synchronized</em> method like this:</p>
  <pre><code>  def writeToFile(bw: BufferedWriter, str: String) = synchronized {
      bw.write(str)
      bw.newLine
    }
  </code></pre>
  <p>From what I researched I can't determine how &quot;safe&quot; this is in regards to scaling my application.  The only examples I can find using <em>synchronized</em> is when accessing collections, not writing to a file.  My application is built in the Play! Framework 2.4.2.</p>