Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()

后端 未结 4 955
傲寒
傲寒 2020-12-29 23:12

My question is : does it make sense to use Executors.newFixedThreadPool(1)??. In two threads (main + oneAnotherThread) scenarios is it efficient to use execut

4条回答
  •  时光取名叫无心
    2020-12-29 23:58

    does it make sense to use Executors.newFixedThreadPool(1)?

    It is essentially the same thing as an Executors.newSingleThreadExecutor() except that the latter is not reconfigurable, as indicated in the javadoc, whereas the former is if you cast it to a ThreadPoolExecutor.

    In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?

    An executor service is a very thin wrapper around a Thread that significantly facilitates the thread lifecycle management. If the only thing you need is to new Thread(runnable).start(); and move on, then there is no real need for an ExecutorService.

    In any most real life cases, the possibility to monitor the life cycle of the tasks (through the returned Futures), the fact that the executor will re-create threads as required in case of uncaught exceptions, the performance gain of recycling threads vs. creating new ones etc. make the executor service a much more powerful solution at little additional cost.

    Bottom line: I don't see any downsides of using an executor service vs. a thread.

    The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start(); goes through the small differences in behaviour between the two options.

提交回复
热议问题