0

I would like to interrupt all threads (“substreams”) of a Java parallelStream according to a condition verified by one of them.

Exemple : a little piece of code to assess time needed to find a six characters password. I iterate from 1 to ~19 billion (a to Z => pow(52,6)) and convert the long toward a string with my function ln.toAString(long), "passwd"=>5705641243).

long limit = 19_770_609_664L;
LongStream.range(0, limit)                  
            .parallel()
            .mapToObj(i -> ln.toAString(i))
            .filter(s -> s.equals("passwd"))
            .findFirst();

When one of the “substream = thread-worker” find the password the others continue to run even if they have no chance to succeed : such a pity ! a way to stop all of the threads workers of the parallelStream when one of them has completed the global goal ?

I tried using a global variable (flag) to consult before continuing or using a Future or a CompletableFuture but :

  1. I know how global variable, side effects ... are bad so I look for an other way
  2. I didn’t really found the way to do this.

I expect that the parallelStream stop as soon as one fork (one the threads workers of the parallelStream) finds the password.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

0 Answers0