Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to prefer the Executors factory methods over instantiating the classes directly?

Is there a reason to prefer doing this:

private static ExecutorService service = Executors.newScheduledThreadPool(10);

over this:

private static ExecutorService service = new ScheduledThreadPoolExecutor(10);
like image 657
Yishai Avatar asked Oct 28 '25 18:10

Yishai


1 Answers

Is there a reason to prefer the Executors factory methods over instantiating the classes directly?

There is no particular reason, no. The Executors static methods are there for convenience and were written to cover a large percentage of the standard use cases.

Although not in the case you mention, usage of some of the other static methods make your code vastly simpler and more readable. For example:

threadPool = Executors.newFixedThreadPool(10);

Versus:

threadPool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue<Runnable>());

The only possible reason I can think of why using the Executors methods could be better is if in future JDK versions, they changed the defaults for some of the underlying ExecutorService classes and the static methods would then be adjusted by Sun/Oracle to make better use of the new constructor arguments and you wouldn't have to change your code.

like image 116
Gray Avatar answered Oct 31 '25 07:10

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!