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
}
}
We can create an instance of ExecutorService in following ways: 2.1. Executors class Executors is a utility class that provides factory methods for creating the implementations of the interface. 2.2. Constructors We can choose an implementation class of ExecutorService interface and create it’s instance directly.
Executors class Executors is a utility class that provides factory methods for creating the implementations of the interface. 2.2. Constructors We can choose an implementation class of ExecutorService interface and create it’s instance directly.
The easiest way to create ExecutorService is to use one of the factory methods of the Executors class. For example, the following line of code will create a thread pool with 10 threads:
The ScheduledExecutorService runs tasks after some predefined delay and/or periodically. Once again, the best way to instantiate a ScheduledExecutorService is to use the factory methods of the Executors class. For this section, we use a ScheduledExecutorService with one thread:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With