My application makes use of a
HandlerThread for a few operations shared across components that need to run on a background thread. Most of the time this thread will be in its wait state.
Can I leave this
HandlerThread running (waiting) in my application, sending messages to it whenever necessary, but never quitting it via
HandlerThread.getLooper().quit()? This could mean that this
HandlerThread would continue to exist in its wait state even after all of my application components have been destroyed.
Initially this seemed like a big no to me—something I definitely would not want to do—but I’m not sure now. When Android kills my process, like it will do when it needs to free up CPU time or memory, it’ll end this thread along with my UI thread. Additionally, the thread will be waiting, so it wont be consuming any CPU time. And beyond that, my application makes use of many
AsyncTasks, which I know utilize a thread pool. From my understanding,
ThreadPoolExecutor, which does not adhere to any application lifecycle callbacks (the threads in the pool when not in use, just sit waiting).
So my question is, can I use a
HandlerThread across multiple application components, never (or rarely) quitting it, and leaving it waiting when not in use, without suffering terrible ill effects?
My personal preference is to create a new thread whenever there is a need for it and clean it up when it’s done. This way I don’t have any problems with multiple components trying to use the same thread at the same time and I keep a “clean ship”. Also Android has the nice AsyncTask which makes this easy for you.
That being said, I see no reason why you can’t reuse your handlerthread for multiple components, provided you regulate access to the thread AND clean it up properly when your activities are destroyed. If I understand this post correctly, your thread may keep running even if all your activities are terminated because your process may keep on running. To solve this, you can set your thread as a daemon thread. Daemon threads are automatically destroyed when the last non-daemon thread in your application is finished.
BTW, alternatively you also might want to consider using a ThreadPoolExecutor