1

I want to run this code in parallel using java parallel stream and update result in two ArrayList. The code given below is working fine except that the non-thread-safety of ArrayList may cause incorrect results, and I don't want to synchronize the ArrayList. Can someone please suggest me a proper way of using parallel stream for my case.

        List<Integer> passedList= new ArrayList<>();
        List<Integer> failedList= new ArrayList<>();

        Integer[] input = {0,1,2,3,4,5,6,7,8,9};
        List<Integer> myList = Arrays.asList(input);

        myList.parallelStream().forEach(element -> {

            if (isSuccess(element)) {//Some SOAP API call.
                passedList.add(element);
            } else {
                failedList.add(element);
            }

        });
        System.out.println(passedList);
        System.out.println(failedList);
1
  • a CompletableFuture might be more appropriate here Commented Jan 11, 2016 at 12:31

1 Answer 1

2

An appropriate solution would be to use Collectors.partitioningBy:

Integer[] input = {0,1,2,3,4,5,6,7,8,9};
List<Integer> myList = Arrays.asList(input);

Map<Boolean, List<Integer>> map = myList.parallelStream()
        .collect(Collectors.partitioningBy(element -> isSuccess(element)));

List<Integer> passedList = map.get(true);
List<Integer> failedList = map.get(false);

This way you will have no thread-safety problems as the task will be decomposed in map-reduce manner: the parts of the input will be processed independently and joined after that. If your isSuccess method is slow you will likely to have performance boost here.

By the way you can create a parallel stream from the original array using Arrays.stream(input).parallel() without necessity to create an intermediate myList.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.