Explain non-interference behavior of Java 8 Streams.
Streams enable you to execute possibly-parallel aggregate operations over a variety of data sources, including
even non-thread-safe collections such as ArrayList. This is possible only if we can prevent interference with the data
source during the execution of a stream pipeline. For most data sources, preventing interference means ensuring that the
data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams
whose sources are concurrent collections, which are specifically designed to handle concurrent modification.
Accordingly, behavioral parameters in stream pipelines whose source might not be concurrent should never modify
the stream's data source. A behavioral parameter is said to interfere with a non-concurrent data source if it modifies, or
causes to be modified, the stream's data source. The need for non-interference applies to all pipelines, not just parallel
ones. Unless the stream source is concurrent, modifying a stream's data source during execution of a stream pipeline can
cause exceptions, incorrect answers, or nonconformant behavior. For well-behaved stream sources, the source can be modified
before the terminal operation commences and those modifications will be reflected in the covered elements.
package com.java2novice.streams;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamConcurrentChangEx {
public static void main(String a[]) {
List<String> vehicles = new ArrayList<>(Arrays.asList("bus", "car", "bicycle", "flight", "train"));
Stream<String> vStream = vehicles.parallelStream();
vehicles.add("bike");
vStream.filter(str->str.length() > 3).map(String::toUpperCase).sorted().forEach(System.out::println);;
}
}
|
|