title: Multiple streams reading from the same file
body: <p>I have a number of input files, which I'm reading in parallel and performing computations on every line that I read. However, for every line (in every file), I need to access one of about hundred files, loop through the entirety it and write the every combination into an output file.</p>
  
  <p>So, basically, I have something like this (<em>note, that I only added the crucial parts of the code</em>):</p>
  
  <pre><code>int numberOfFiles = (int) new File("path/").listFiles().length;
  
  IntStream.range(0, numberOfFiles).parallel().forEach(k -&gt; { 
      BufferedWriter bw = null;
      BufferedReader br = null;
      try {
          br = new BufferedReader(new FileReader(new File("priorityQueuePreTerminal"+k+".txt")));
          bw = new BufferedWriter(new FileWriter(new File("priorityQueuePostTerminal"+k+".txt"), true));
          ...
          try {
              while( (line = br.readLine()) != null ){ 
              ...
                  BufferedReader br2 = new BufferedReader(new FileReader(new File("shared/"+i+".txt")));
                  while( (line2 = br2.readLine()) != null ){ 
                      bw.write(...);
                  }
              }
          } catch (Exception e) { } finally { br2.close(); }
      } catch (Exception e) { } finally { br.close(); bw.close(); }
  });
  </code></pre>
  
  <p>What essentially happens, is that two input files can read from the same one of those hundred shared files, at the same time. 
  The end result is, that one of the output files is always fully completed, like it should be, while all the other output files have the starting few lines, and then they end prematurely.</p>
  
  <p>Am I even able to read from the same shared file by multiple streams (I was under the impression that reading from the same file by multiple resources was fine, but writing could be problematic)? Is there an equivalent to <code>synchronized</code> in Java 8 streams, to make sure that one stream is currently reading only from one file? </p>