Search code examples
javajava-streamoutputstreamfileoutputstreambufferedwriter

multi thread write only one outputstream and data loss


I run the five threads that generate the random string data and then write only one output stream. after the program is finished, a few data was lost.

I simplify my code.

new Thread(() -> {
  stream.write(RANDOM_STRING + "\n)
).start();
class Stream {
  String buffer = "";

  Stream() {
    new Thread(() -> {
      BufferedOutputStream bs
       = new BufferedOutputStream(new FileOutputStream("PATH");
      bs.wrtie(buffer.getBytes());  // point 1
      buffer = ""                   // point 2
      bs.close();
    }).start();
  }
  public void write(String input) {
    buffer += input;
  }
}

I think data loss's cause is between point 1 and 2. I think If I use the indexing data structure for checking what data was consumed, It can be solved. but is there any better way to solve this problem? Please help me. Thanks.


Solution

  • Try to use ConcurrentLinkedQueue<String> for buffer, with methods offer and poll instead of += and = "" on String reference.