JAVA8 added the Stream API, which gives programmers a foreach method for traversing collections: java.util.stream.stream # foreach.

So what do you know about this Foreach method? Let’s answer these questions.

Question 1: Is foreach sequential consumption

As title. Is foreach sequential consumption?

My answer is: not necessarily.

The order in which elements are consumed is not guaranteed when the java.util.stream. stream #forEach method is called in a parallel stream.

Use the java.util.stream. stream #forEachOrdered method if you need to ensure sequential consumption of elements in a parallel stream.

Question 2: Is Foreach a quick failure

Without further ado, directly on the code, seeing is believing:

We can know that the program by example, it is really throw ConcurrentModificationException is unusual, but the Java. Util. Stream. Stream# forEach method is the timing of the thrown exception in the consumer after the original all of the elements, Instead of the fast failure mode of the iterator.

Question 3: What happens when you add elements before foreach

What is the result of executing the following code? Will exceptions be thrown?

public static void main(String[] args) {
  List<Integer> list = new ArrayList<>(Arrays.asList(1.2.3.4));
  Stream<Integer> stream = list.stream();
  list.add(6);
  stream.forEach(System.out::println);
}
Copy the code

Think about it for a minute.

The correct answer is: no exceptions are thrown, and the modified elements are output. The result is as follows:

homework

What is the underlying implementation of the java.util.stream. stream #forEach method? Interested students can have a look at the source code, source code analysis will be updated in the next issue.


Welcome to pay attention to personal public account: