title: lambda foreach parallelStream creating less data than expected
body: <p>I'm trying to implement a <strong>lambda foreach parallel Stream of an arraylist</strong> to improve performance of an existing application.</p>
  
  <p>So far the <strong>foreach iteration without a parallel Stream</strong> creates the expected amount of data written into a database.</p>
  
  <p>But when <strong>I switch to a parallelStream</strong> it always <strong>writes less rows</strong> into the database. Let's say from 10.000 expected, nearly 7000 rows, but result varies here.</p>
  
  <p>Any idea what I am missing here, data race conditions, or must I work with locks and synchronized?</p>
  
  <p>The code does something like this basically:</p>
  
  <pre><code>// Create Persons from an arraylist of data
  
  arrayList.parallelStream()
            .filter(d -&gt; d.personShouldBeCreated())
            .forEach(d -&gt; {
  
     // Create a Person
     // Fill it's properties
     // Update object, what writes it into a DB
  
    }
  );
  </code></pre>
  
  <p><strong>Things I tried so far</strong></p>
  
  <p>Collect the result in an new List with...</p>
  
  <pre><code>collect(Collectors.toList())
  </code></pre>
  
  <p>...and then iterating over the new list and executing the logic, described in the first code snippet.
  The size of the new 'collected' <strong>ArrayList matches with the expected result, but at the end there is still less data created</strong> in the database.</p>
  
  <p><strong>Update/Solution:</strong></p>
  
  <p>Based on the answer I marked (and also the hints in the comments)  <strong>concerning non-thread safe parts</strong> in that code, I implemented it as the following, what finally gives me the expected amount of data. Performance has improved, it takes now only 1/3 of the implementation before.</p>
  
  <pre><code>StringBuffer sb = new StringBuffer();
  arrayList()
    .parallelStream()
    .filter(d-&gt; d.toBeCreated())
    .forEach(d -&gt;
      sb.append(
              // Build an application specific XML for inserting or importing data
      )
    );
  </code></pre>
  
  <p>The application specific part is an XML based data import api, but I think this could be done in plain SQL JDBC inserts.</p>