简体   繁体   中英

ParallelStream with filter chaining

Does filter chaining change the outcome if i use parallelStream() instead of stream() ?

I tried with a few thousand records, and the output appeared consistent over a few iterations. But since this involves threads,(and I could not find enough relevant material that talks about this combination) I want to make doubly sure that parallel stream does not impact the output of filter chaining in any way. Example code:

List<Element> list = myList.parallelStream()
      .filter(element -> element.getId() > 10)
      .filter(element -> element.getName().contains("something"))
      .collect(Collectors.toList());

Short answer: No .

The filter operation as documented expects a non-interferening and stateless predicate to apply to each element to determine if it should be included as part of the new stream.

Few aspects that you shall consider for that are -

  1. With an exception to concurrent collections(what do you choose as myList in the existing code to be) -

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline.

  1. The state of the data sources ( myList and its element s within your filter operations are not mutated)

Note also that attempting to access mutable state from behavioral parameters presents you with a bad choice with respect to safety and performance;

Moreover, think around it, what is it in your filter operation that would be impacted by multiple threads. Given the current code, nothing functionally, as long as both the operations are executed, you would get a consistent result regardless of the thread(s) executing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM