Stream.sorted(...).forEach(...) issue (parallel streams)

Georgiy Rakov georgiy.rakov at oracle.com
Wed Jan 30 05:45:23 PST 2013


Hello,

it seems there is a bug in promoted b74 while chaining sorted and 
forEach being applied to parallel streams.

Let's consider following code:

    public class SortedIssue2 {
         public static void main(String[]args) {
             Integer[] baseData = new Integer[]{1, 4, 3, 2, 9, 7};
             Comparator<Integer> cmp = (a, b) -> a - b;

             List<Integer> sorted = new ArrayList<>();

            
    Arrays.parallelStream(baseData).sorted(cmp).forEach(sorted::add);
             System.out.println("incorrect: " +
    Arrays.toString(sorted.toArray()));

             //Following line is just intended for providing the correct
    result in order to compare with incorrect one
             System.out.println("correct:   " +
    Arrays.toString(Arrays.parallelStream(baseData).sorted(cmp).toArray()));
         }
    }

This code produces following output:

    incorrect: [1, _*4, 2*_, 7, _*9, 3*_]
    correct:   [1, 2, 3, 4, 7, 9]

The result [1, _*4, 2*_, 7, _*9, 3*_]is obviously incorrect.
BTW: the first line of the output is non deterministic. Provided the 
code is run several times different output is produced each time. For 
instance:

    incorrect: [3, 2, 7, 9, 4]
    correct: [1, 2, 3, 4, 7, 9]

    incorrect: [1, 4, 7, 2, 9, 3]
    correct: [1, 2, 3, 4, 7, 9]

    incorrect: [4, 2, 3, 7, 9]
    correct: [1, 2, 3, 4, 7, 9]

    incorrect: [1, 2, 3, 7, 4]
    correct: [1, 2, 3, 4, 7, 9]

After changing parallel mode to sequential the code works fine. This 
issue is reproduced on Windows 7x64.

Please confirm it's a bug and it will be fixed.

The code is attached for your convenience.

Thank you,
Georgiy.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: SortedIssue2.java
Url: http://mail.openjdk.java.net/pipermail/lambda-dev/attachments/20130130/7677d940/SortedIssue2.java 


More information about the lambda-dev mailing list