Reason for calling shutdown() on ExecutorService

后端 未结 5 1737
-上瘾入骨i
-上瘾入骨i 2020-12-04 07:46

I was reading about it quite a bit in past couple hours, and I simply cannot see any reason (valid reason) to call shutdown() on the Exec

5条回答
  •  萌比男神i
    2020-12-04 08:16

    Isn't the whole idea for the ExecutorService to reuse the threads? So why destroy the ExecutorService so soon?

    Yes. You should not destroy and re-create ExecutorService frequently. Initialize ExecutorService when you require (mostly on start-up) and keep it active until you are done with it.

    Isn't it a rational way to simply create ExecutorService (or couple depending on how many you need), then during the application running pass to them the tasks once they come along, and then on the application exit or some other important stages shutdown those executors?

    Yes. It's rational to shutdown ExecutorService on important stages like application exit etc.

    Second side question, a bit smaller deals with android platform. IF some of you will say that it's not best idea to shutdown executors every time, and you program on android, could you tell me how you handle those shutdowns (to be specific, when you execute them) when we deal with different events of application life cycle.

    Assume that ExecutorService is shared across different Activities in your application. Each activity will be paused/resumed at different intervals of time and still you need one ExecutorService per your application.

    Instead of managing the state of ExecutorService in Activity life cycle methods, move ExecutorService management ( Creation/Shutdown) to your custom Service.

    Create ExecutorService in Service => onCreate() and shutdown it properly in onDestroy()

    Recommended way of shutting down ExecutorService :

    How to properly shutdown java ExecutorService

提交回复
热议问题