title: How collectors are used when turning the stream in parallel
body: <p>I actually tried to answer this question <a href="https://stackoverflow.com/questions/30170089/how-to-skip-even-lines-of-a-streamstring-obtained-from-the-files-lines/30170928">How to skip even lines of a Stream&lt;String&gt; obtained from the Files.lines</a>. So I though this collector wouldn't work well in parallel:</p>
  
  <pre><code>private static Collector&lt;String, ?, List&lt;String&gt;&gt; oddLines() {
      int[] counter = {1};
      return Collector.of(ArrayList::new,
              (l, line) -&gt; {
                  if (counter[0] % 2 == 1) l.add(line);
                  counter[0]++;
              },
              (l1, l2) -&gt; {
                  l1.addAll(l2);
                  return l1;
              });
  }
  </code></pre>
  
  <p>but it works. </p>
  
  <p><strong>EDIT: It didn't actually work; I got fooled by the fact that my input set was too small to trigger any parallelism; see discussion in comments</strong>.</p>
  
  <p>I thought it wouldn't work because of the two following plans of executions comes to my mind.</p>
  
  <hr/>
  
  <h2>1. The <code>counter</code> array is shared among all threads.</h2>
  
  <p>Thread t1 read the first element of the Stream, so the if condition is satisfied. It adds the first element to its list. Then the execution stops before he has the time to update the array value.</p>
  
  <p>Thread t2, which says started at the 4th element of the stream add it to its list. So we end up with a non-wanted element.</p>
  
  <p>Of course since this collector seems to works, I guess it doesn't work like that. And the updates are not atomic anyway.</p>
  
  <hr/>
  
  <h2>2. Each Thread has its own copy of the array</h2>
  
  <p>In this case there is no more problems for the update, but nothing prevents me that the thread t2 will not start at the 4th element of the stream. So he doesn't work like that either.</p>
  
  <p><hr/>
  So it seems that it doesn't work like that at all, which brings me to the question... how the collector is used in parallel?</p>
  
  <p>Can someone explain me basically how it works and why my collector works when ran in parallel?</p>
  
  <p>Thank you very much!</p>