Search code examples
javaconcurrencyjava.util.concurrent

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);

Solution

  • 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.