ExecutorService - create new instances in method vs one per class

concurrency, executorservice, java, multithreading, threadpool

Solution

In your first code snippet the `ExecutorService` is local, i.e. a new `ExecutorService` is created on each method call and the `ExecutorService` is terminated at the end of the method. As a consequence the threads aren't reused when the method runs the next time. In the second snippet the `ExecutorService` and its threads are kept as long as the `NotificationService` instance is alive. As you can see there are not only less instances of `ExecutorService` to be GC'd but there are less threads to create and they can be reused. As an additional bonus the second method does not incur any no warmup time for thread creation after the `ExecutorService` has been created.

If you have multiple instances of `NotificationService` you should declare `notificationsPool` as `static` in order to share the pool and its threads between all the instances.

If the amount of threads needed varies depending on the amount of notifications that have to be sent, use a cached thread pool (`ExecutorService#newCachedThreadPool()`), maybe with an upper limit.

Problem

Should I create new ExecutorService in every method call or use one per class? Which is preferred option in terms of performance? ``` public class NotificationService { public void sendNotification(User recipient) { ExecutorService notificationsPool = Executors.newFixedThreadPool(10); // code notificationsPool.shutdown(); } } ``` Or ``` public class NotificationService { ExecutorService notificationsPool = Executors.newFixedThreadPool(10); public void sendNotification(User recipient) { // code } } ```

Original source