Stream allMatch issue

Georgiy Rakov georgiy.rakov at oracle.com
Tue Nov 27 09:25:53 PST 2012


Hello,

the code below causes ConcurrentModificationException to be thrown with 
following stack trace:

    Exception in thread "main" java.util.ConcurrentModificationException
         at
    java.util.ArrayList$Itr.checkForComodification(ArrayList.java:818)
         at java.util.ArrayList$Itr.next(ArrayList.java:790)
         at AllMatchBehaviour.main(AllMatchBehaviour.java:34)

Obviously the emphasized piece of code is one part of the cause (see below).

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.functions.Predicate;

    public class AllMatchBehavior {
         public static void main(String[] args) {
             ArrayList<Integer> calledObjects = new ArrayList<>();
             List<Integer> streamContent = new ArrayList<>();
             for (int i = 0; i < 10000; ++i) {
                 streamContent.add(i);
             }

             Predicate<Integer> p = i -> {
                 synchronized (calledObjects) {
                     calledObjects.add(i);
                 }
                 return i < 5000;
             };

             boolean result = Arrays.parallel(streamContent.toArray(new
    Integer[]{})).allMatch(p);

             String asStr = "";
    *        for (Integer i : calledObjects) {*
    *            asStr += " " + i;*
    *        }*
             System.out.println("called objects: " + asStr);
         }
    }

I could guess that exception is thrown because some stream chunks are 
still processed after the result have been received from allMatch.
Is such behavior considered to be faulty? Please give your comments.

The same things happen to noneMatch and anyMatch methods by the way.

The source code is attached for your convenience.

Thanks, Georgiy.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: AllMatchBehavior.java
Url: http://mail.openjdk.java.net/pipermail/lambda-dev/attachments/20121127/d5ac8919/AllMatchBehavior.java 


More information about the lambda-dev mailing list