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
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())
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.