0

I found this code and have a hard time understanding how this makes sense. As I understand it, this will create a number of threads and then execute the tasks on a single one of those threads and wait for the result, and then stop the threads. Is there something I am missing?

return ThreadPoolUtils.parallel(parallelThreads)
                                  .execute(() -> someList.parallelStream().map(someFunction).collect(toList()))

With this definition of ThreadPoolUtils:

@Slf4j
@Builder
public class ThreadPoolUtils {
    private final ExecutorService executorService;
    public static ThreadPoolUtils parallel(int maxThreads) {
        return ThreadPoolUtils.builder()
                              .executorService(new ForkJoinPool(maxThreads))
                              .build();
    }
    public <T> T execute(Callable<T> callable) throws ThreadPoolException {
        try {
            return executorService.submit(callable)
                                  .get();
        } catch (ExecutionException e) {
            throw new ThreadPoolException("ExecutionException occurred during executing Thread", e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ThreadPoolException("InterruptedException occurred during executing Thread", e);
        } finally {
            executorService.shutdown();
        }
    }
}
Koen Hendrikx
  • 2,243
  • 2
  • 9
  • 7
  • It's using an [undocumented trick](https://stackoverflow.com/questions/52836178/parallelstream-queue-task-in-commonpool-rather-than-the-custom-pool) to run `parallelStream()` in a different threadpool than the common pool. – Kayaman Aug 30 '23 at 08:54

0 Answers0