title: Multiple threads using System.out.println in Java
body: <p>I have a multi-threaded Java application that will output information about a message it receives to the console for debugging purposes.  Each time the application receives a message, it will call a <code>System.out.println(String)</code> on the message.  </p>
  
  <p>The problem that I am having is that if the application gets flooded with messages, <code>System.out.println()</code> prints erroneous information (like old buffer information).  This is leading me to wonder if there is a threading issue where multiple threads are calling the <code>println</code> function at one time, and not properly flushing the buffer.</p>
  
  <p>In my main program (thread), I have something to the effect of:</p>
  
  <pre><code>while(iterator.hasNext())
  {
      SelectionKey key = iterator.next();
  
      channel.receive(buffer);     // The buffer is a ByteBuffer.
      buffer.flip();
  
      new Thread(new ThreadToPrintTheMessage(buffer)).start();
  
      buffer.clear();
  
      iterator.remove();
  }
  </code></pre>
  
  <p>In my thread, I have something to the effect of:</p>
  
  <pre><code>@Override
  public void run()
  {
      System.out.println(message);
      System.out.flush();   // I have better results with this.  But, it doesn't
                            // fully resolve the issue.
  }
  </code></pre>
  
  <p>Is there a simple way for me to have multiple threads print out to the console at one time without the buffers containing old information?</p>
  
  <p>Thanks</p>
  
  <p><strong>EDIT: updated the code in the main thread to be more representative of what my program is doing.</strong></p>