When to shutdown executorservice in android application

前端 未结 2 1573
孤城傲影
孤城傲影 2021-02-13 14:09

Lets assume I\'m planning to use one executorservice in my entire application, to which I\'m sending new runnable\'s or callable\'s to execute/submit, and I ommit to shutdown ri

相关标签:
2条回答
  • 2021-02-13 14:41

    You can do one work around. Create the executor as daemon. Then it will automatically end when your application exits. You don't have to explicitly call the shutdown.

     ExecutorService es = Executors.newSingleThreadExecutor( new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });
    
    0 讨论(0)
  • 2021-02-13 14:55

    I have a singleton instance of an ExecutorService which is scoped to the Android application instance via Dagger's object graph. So the instance lives as long as the Application object itself. Since Android's Application class offers no onDestroy() callback, it is never known when shutdown() should be called on the ExecutorService.

    As I was afraid of memory leaks, I was also looking into ThreadPoolExecutor and playing with it to find out. This is what I found: Executors.newCachedThreadPool() creates a ThreadPoolExecutor with the following parameters:

    ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>())
    

    That is a corePoolSize of 0, which means that a minimum number of 0 worker threads is kept alive, so none. When the TPE (a.k.a ExecutorService) executes a task, it creates a worker thread and adds it to the pool. Now when no new task comes in during the timeout of 60 secs, the (still kept alive) worker thread is terminated and removed from the pool (cache).

    For me that means that there won't be a memory leak, even when shutdown() is never called on the ExecutorService, as all worker threads that ever exist, time out and will be removed from the pool when no new task come in during the timeout period. I guess that that way, there wont be any references to worker threads left in the pool and so the GC can clean up the TPE instance.

    Feel free to correct me if I'm wrong.

    0 讨论(0)
提交回复
热议问题