This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Java8’s new features, lambda expressions, and various sequences of operations bring simplicity to the code, but simplicity also brings complexity to troubleshooting. It’s a trade-off between good and bad, and we’re stuck today with its streaming.

Most of the time, we use Stream to do some processing, but there are always people who, I’m talking about people who are obsessed with multithreading, use it, cause thread-safety problems, or even data loss, or for people who are unfamiliar with it (I just don’t know anything about parallelStream), see someone else’s code and get confused;

  • A Stream is a sequential Stream that is a source from this collection and only iterates, splits, or queries the splitter to get an estimated size after terminal operations on the Stream pipe have begun. The official recommendation is ** It is strongly recommended that splitters report IMMUTABLE or CONCURRENT characteristics, or are late bound. Otherwise, you should use stream(Supplier, int, Boolean) to reduce the range of potential interference with the source. ** If you use stream() here, it will process data as a sequential stream because the default implementation creates a sequential stream from the set’s Spliterator;
  • ParallelStream is parallel and returns a possible parallelStream with this collection as its source. Allow this method to return a sequential Stream. If you use parallelStream() here, it will do the data processing as a parallelStream, because the default implementation creates a parallelStream from the collection’s Spliterator;

Why? Because whether it’s Stream or parallelStream, they’re actually calling the same method, just with different arguments, and they’re both going to end up calling it, right

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) {
        Objects.requireNonNull(spliterator);
        return new ReferencePipeline.Head<>(spliterator,
                                            StreamOpFlag.fromCharacteristics(spliterator),
                                            parallel);
    }
Copy the code

When PARALLEL is true, the returned stream is a parallel stream; If false, the returned stream is a sequential stream

You can also use parallelStream to add values to a collection that is not thread safe. You can also use parallelStream to add values to a collection that is not thread safe. You again outside security, but you do not have noticed, a simple not thread-safe collections, will cause the collection expansion does not lead to overflow in time, causing the add same place empty value problems, throw out the Java. Util. ConcurrentModificationException anomaly information, and so on;

Let’s use two examples to illustrate how these two mechanisms work

Stream

List<Character> numbers = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g');
        numbers.stream().forEach(charat -> System.out.print(charat +" ")
Copy the code

A B C D E F G

parallelStream

List<Character> numbers = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g');
        numbers.parallelStream().forEach(charat -> System.out.println(charat +" "+Thread.currentThread().getName())
        );
Copy the code

The result: E main

g ForkJoinPool.commonPool-worker-2 

b ForkJoinPool.commonPool-worker-1

 f ForkJoinPool.commonPool-worker-2 

c ForkJoinPool.commonPool-worker-1 

a ForkJoinPool.commonPool-worker-2

 d main

So here we’re calling three threads to process the data, so you can see what happens if you use a non-thread safe set to process complex business data, so let’s pretend we don’t know about Stream and try to do it with Stream, which happens to be sequential, So we don’t need to lock the Stream, because the Stream sequence is equivalent to a lock; And when we use parallelStream, in some cases it can cause thread overuse and affect resource allocation,

These problems are very difficult to troubleshoot, unless you have a lot of experience,

Finally, happy Chinese Valentine’s Day