Skip to content
Advertisement

How to run Executor Service on a list and perform some action in Java

I have a list of items which I want to run an executor service to perform some expensive action:

var myList = Arrays.asList("item1", "item2");
var es = Executors.newFixedThreadPool(10);

myList.foreach(item -> {
    es.submit(() -> {
        performExpensiveAction(item);
    })
})

es.shutdown();

Say I have 100 items in the list, I expect the es to performExpensiveAction on all 100 items but it only performs the action on 10 items.

Advertisement

Answer

You should consider using invokeAll instead shutdown.

The shutdown() method will allow previously submitted tasks to execute before terminating,

while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks.

Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (invokeAll waiting for all)

Documentation

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement