TheOnlyKiller
TheOnlyKiller

Reputation: 21

How to call a function in parallel using list?

I have a list with values and I want to call a function using executor service with that list the function has only single parameter string. For example I have -

private List<String> namesList = new ArrayList<>();

private ExecutorService exeService = Executors.newFixedThreadPool(10);

private void printNames(String name);

I want to call this function printNames using list values in parallel with executor service i.e if my list has size of 10 then this function should be called parallelly for that list data.

Can it be done inputs will be very helpful ?

Upvotes: 0

Views: 1055

Answers (1)

Shmulik Klein
Shmulik Klein

Reputation: 3914

If you would like to use an executor service for executing your method for each list entry, you'll have to first make your method to be executed by a Runnable or Callable object:

Runnable task = () -> printNames(name);

and then submit it to the executor service:

executorService.submit(task);
class NamePrinter {
  public static void main(String[] args) {
    List<String> names = List.of("Qui-Gon Jinn", "Mace Windu", "Ahsoka Tano", "Plo Koon", "Kit Fisto", "Aalya Secura");
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (String name : names) {
      executorService.submit(() -> printName(name));
    }
    executorService.shutdown();
  }

  public static void printName(String name) {
    System.out.println(name + " was executed by " + Thread.currentThread().getName());
  }
}

You should consider using parallelStream for processing the list in parallel:

names.parallelStream().forEach(NamePrinter::printName);

This will use the ForkJoinPool executor service behind the scenes.

Upvotes: 3

Related Questions