Java Reference
In-Depth Information
If you look at the stack trace in Listing 7-2, you can begin to see some of the stack trace noise generated
by Java's lambda implementation. We will get into why that is there and how to read it in the next chapter.
What we can tell already, however, is that we get the exact source lines from the lambda itself
(the lambda$main$0 lines), along with the location where the lambda was called (the Listing1.call line).
This should make sense, since calling the lambda is simply executing the function interface method for it
(the Listing1$$Lambda$1/558638686.accept line). The original exception is also given to us in the “Caused
by” line, just like we are used to. All in all, this is very familiar and comfortable.
However, things become much more interesting when you start using parallel streams. In this case,
the exception will be thrown from the context of the ForkJoinWorkThread instances. This is going to create
significantly more noise in the stack trace, and it obscures our ability to backtrack the call stack. To see where
the difficulty lies, let's build out an example. In this example, we will explode when we execute the 100th
line. Let's take a look at the result in Listing 7-3.
Listing 7-3. Unhandled Exception Terminating a Stream
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
import java.util.stream.*;
public class Listing3 {
public static InputStream generateInputStream() {
return new ByteArrayInputStream("foobar".getBytes());
}
public static Stream<Integer> generateParallelStream() {
final int elements = 1000;
List<Integer> toReturn = new ArrayList<>(elements);
for (int i = 0; i < elements; i++) {
toReturn.add(i);
}
return toReturn.parallelStream();
}
public static Function<Integer, Integer> generateMap() {
AtomicInteger counter = new AtomicInteger(0);
return i -> {
int count = counter.incrementAndGet();
try (InputStream in = Listing3.generateInputStream()) {
if (i == 100) {
throw new IOException(
"And with a kiss, I die! (After " + count + " executions)");
}
return i;
 
Search WWH ::




Custom Search