4

I have Googled to see what is thrown from a forEach method from a parallel Stream when a Consumer throws an exception, and haven't found anything about it. Does it throw something similar to C#'s AggregateException, or something else?

0

2 Answers 2

2

Exceptions are relayed to the caller, as per http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinTask.html#fork()

Rethrown exceptions behave in the same way as regular exceptions, but, when possible, contain stack traces (as displayed for example using ex.printStackTrace()) of both the thread that initiated the computation as well as the thread actually encountering the exception; minimally only the latter.

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

Comments

1

According to the following code, the exception that was thrown is thrown on the main thread:

final int maxCount = 100;
    List<Integer> dummy = new ArrayList<>(maxCount);
    for (int i = 0; i < maxCount; i++) {
        dummy.add(i);
    }
    Thread mainThread = Thread.currentThread();
    AtomicInteger times = new AtomicInteger();
    dummy.parallelStream().forEach(item->{
        if (times.incrementAndGet() > 5 && Thread.currentThread() != mainThread){
            throw new NullPointerException();
        }
    });

3 Comments

Note that even if the exception is thrown the forEach continues to process all jobs. Therefore the NullPointerException is thrown 95 times...
@Robert so if there is a catch for the exception with some logic, like printing the stacktrace and then doing something, that also will be happening 95 times right? Instead when using a normal stream (not parallel) this would only happen once, like with a normal for loop
@BugsForBreakfast It seems my comment was not correct. It seems parallelStream (tested on Java 11 & 17) stops execution when the first exception occurred. So only the jobs already running in parallel will also throw the Exception. So it depends on the number of threads used by parallelStream (which means it depends on the number of CPU cores).

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.