Daniel L. Daniel L. - 1 month ago 10
Android Question

Should I manually close HandlerThreads created by my application when destroying the activity?

My app is composed of a single

Activity
. In this activity, I'm creating multiple
HandlerThread
s which run in a loop to do socket blocking operations.

Currently I post a quit message to everyone of these
HandlerThread
s during my
Activity.onDestroy()
.

Sometimes, when I open my app, close it and relaunch it, it crashes (many time due to posting a message to a handler thread which is not running).

My question is: What is the right way to close
HandlerThread
when I close my app?
(Note that those threads might be blocking on a socket operation).

EDIT: More information:
I have a pool of Handler Threads which is initiated in onCreate (No problem when I'm launching my app at the first time).

Each handler runnable loop is wrapped with an

if (shouldRun) {
//body
}
else {
close();
}


statement.

the close method remove all pending messages and runnables and post a message to the handler that will cause him to call its
looper.quit()
.
This way, if the current handler thread is blocked by IO operation, only once it will finish it he will quit().

Answer
  • You must have some inconsistency there, otherwise your App wouldn't crash. Are you sure that a HandlerThread which is not running is really the reason? Don't you create HandlerThread objects when your Activity is created?
  • If your HandlerThreads are waiting on I/O operations, I would consider to try and interrupt them. Simply removing callbacks and messages and asking the Looper to quit, even sending temrination messages to the Handler, will do nothing. The HandlerThread onbject will still be around until Android kills the process (which may or may not occur). This means that "your app will collect zombie HandlerThread objects" which are probably unreachable. Unless, of course, you can send those HandlerThreads a termination message which arrives on the channel they block on.
  • It would be much better to re-use the HandlerThread objects. A Service might be the right model to do this.
  • Also, if Threads survive your Activity, you need to inform them that their communication peer (your Activity) is gone. Otherwise, they may refer to something which is already gone.
Comments