0

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 ?

5
  • Which part are you stuck on? Commented Jan 21, 2022 at 3:37
  • @tgdavies I have a thread pool and i have a list the part i am stuck on is calling the function in parallel using executor service in parallel. Commented Jan 21, 2022 at 4:08
  • Use a loop and pass a Runnable to the executor for each item in your list. Commented Jan 21, 2022 at 4:18
  • @tgdavies will this help - for(String s1: nameList) { exeService.submit(() -> { runBatch(s1); }); } Commented Jan 21, 2022 at 4:25
  • @tgdavies can you please elaborate a bit more on your answer as I am pretty much new to executor service in java ? Commented Jan 21, 2022 at 4:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.