If your Stream
has only two elements, it's likely the stream framework will not create two threads to process those two elements. Therefore, once an exception is thrown for the first element, the second won't be processed.
Actually, when I tried similar code to yours, but without the exception, I found out the 2 elements are actually processed on the main
thread:
public static int function(int key) {
System.out.print("printing: " + key + " " + Thread.currentThread ().getName () + " ");
return key;
}
public static void main (java.lang.String[] args)
{
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 1 ; i <= 2 ; i ++) {
map.put(i,i);
}
map.entrySet().parallelStream()
.map(batch -> function(batch.getKey()))
.collect(Collectors.toList());
}
This output:
printing: 1 main printing: 2 main
Only when the Stream
is larger, the work is split into multiple threads, so the exception thrown for one element won't affect the processing of the rest.
If I increase the size of the Stream
to 5, I get:
printing: 1 ForkJoinPool.commonPool-worker-1 printing: 2 ForkJoinPool.commonPool-worker-1 printing: 3 ForkJoinPool.commonPool-worker-1 printing: 4 main printing: 5 main
So now the work is divided into two threads.
And if I throw a RuntimeException
for the first element, I get:
printing: 4 main printing: 5 main Exception in thread "main" java.lang.RuntimeException
As you can see, the elements that were assigned to the thread where the exception was thrown were not processed, but the elements assigned to the other thread were processed.