-6

I'm reading this excellent series of articles about stream.

Can a definition to anti-pattern in the context of java 8 -Stream will be a stream that does not produce a valid result using parrallel and a valid result using sequential calculation?

Example from the article:

A good pattern: (the stream can be calculated sequentaly and in parallel)

Set<String> uniqueStrings = strings.stream().collect(
    HashSet::new,
    HashSet::add,
    HashSet::addAll);

An anti-pattern: (the stream be calculated only sequentaly and not in parallel)

Set<String> set = new HashSet<>();
strings.stream().forEach(s -> set.add(s));
2
  • 2
    see Discuss this ${blog}
    – gnat
    May 23, 2017 at 18:59
  • hi @gnat , I specified example and my own definition to stream anti pattern. I would like to read more opinitions about that.
    – Stav Alfi
    May 23, 2017 at 19:07

1 Answer 1

2

You've misunderstood why this is being called an anti-pattern.

Can a definition to anti-pattern in the context of java 8 -Stream will be a stream that does not produce a valid result using parrallel and a valid result using sequential calculation?

Not producing a valid result would be a bug. Not an anti-pattern.

The parallel vs sequential issue is purely about efficiency. The only way this issue causes a bug is if resources are overwhelmed.

What this is about is writing code that is flexible enough that it can be automatically optimized to take advantage of a parallel environment. The sequential code can't.

There is no such thing as an anti-pattern without context and purpose. Here that's wanting the code to be able to take advantage of parallelism. Either code example works just as well on a single core in a single thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.