javamultithreadingexecutorservicefork-joinspliterator

Simple multi-threaded Java app - ExecutorService? Fork/Join? Spliterators?


I am writing a command-line application in Java 8. There's a part that involves some computation, and I believe it could benefit from running in parallel using multiple threads. However, I have not much experience in writing multi-threaded applications, so I hope you could steer me in the right direction how should I design the parallel part of my code.

For simplicity, let's pretend the method in question receives a relatively big array of longs, and it should return a Set containing only prime numbers:

public final static boolean checkIfNumberIsPrime(long number) {
  // algorithm implementation, not important here
  // ...
}

// a single-threaded version
public Set<Long> extractPrimeNumbers(long[] inputArray) {
  Set<Long> result = new HashSet<>();
  for (long number : inputArray) {
    if (checkIfNumberIsPrime(number)) {
      result.add(number);
    }
  }
  return result;
}

Now, I would like to refactor method extractPrimeNumbers() in such way that it would be executed by four threads in parallel, and when all of them are finished, return the result. Off the top of my head, I have the following questions:


Solution

  • Parallel stream

    Use none of these. Parallel streams are going to be enough to deal with this problem much more straightforwardly than any of the alternatives you list.

    return Arrays.parallelStream(inputArray)
      .filter(n -> checkIfNumberIsPrime(n))
      .boxed()
      .collect(Collectors.toSet());
    

    For more info, see The Java™ Tutorials > Aggregate Operations > Parallelism.