title: How to safely flush a buffer from a different thread, without synchronized methods?
body: <p>There are multiple threads, say B, C and D, each writing small packets of data to a buffer at a high frequency. They own their buffer and nobody else ever writes to it. Writing must be as fast as possible, and I've determined that using <code>synchronized</code> makes it unacceptably slow.</p>
  
  <p>The buffers are simply byte arrays, along with the index of the first free element:</p>
  
  <pre><code>byte[] buffer;
  int index;
  
  public void write(byte[] data) {
      // some checking that the buffer won't overflow... not important now
      System.arraycopy(data, 0, buffer, index, data.length);
      index += data.length;
  }
  </code></pre>
  
  <p>Every once in a while, thread A comes along to flush everybody's buffer to a file. It's okay if this part has some overhead, so using <code>synchronized</code> here is no problem.</p>
  
  <p>Now the trouble is, that some other thread might be writing to a buffer, while thread A is flushing it. This means that two threads attempt to write to <code>index</code> around the same time. That would lead to data corruption, which I would like to prevent, but <em>without</em> using <code>synchronized</code> in the <code>write()</code> method.</p>
  
  <p>I've got the feeling that, using the right order of operations and probably some <code>volatile</code> fields, this must be possible. Any bright ideas?</p>