Search code examples
androidmultithreadingandroid-handlerandroid-looper

Does declaring multiple Handler instance create multiple queue?


I have a class with multiple functions, each function were containing a separate handler to execute a runnable. Recently I realized that we must remove all the callbacks on the onDestroy method to avoid memory leaks, so for that, I declared a class-level handler and used the same handler to post runnable in all the functions.

Now my confusion is, what happens if we use the same instance of Handler for multiple runnable compared to a separate handler instance for each runnable?


Solution

  • No matter how many handlers you have, all those handlers will post their messages to the same queue which is main thread queue by default, unless you attach the handlers to different looper objects excplicitly. To illustrate in code:

    // This handler will be attached to the main thread's looper,
    // hence to its queue implicitly but however this constructor
    // is deprecated and is not recommended.
    Handler handlerMain = new Handler();
    
    // This handler will be attached to the main thread's looper
    // object explicitly and this is the recommended way by Google.
    Handler handlerMain = new Handler(Looper.getMainLooper()); 
    
    // Another handler will be attached to the main thread's looper object.
    Handler handlerMain2 = new Handler(Looper.getMainLooper()); 
    
    // This is a custom handler thread whis has a looper object same as the apllication's main (ui) thread. But this one will be a background thread.
    HandlerThread mHandlerThread = new HandlerThread("MyHandlerThread");
    mHandlerThread.start();
    
    // Now this handler will post messages to the mHandlerThread's queue.
    // Hence you cannot access directly to the UI elements from this thread,
    // you must post the ui touching codes to the main thread's queue.
    Handler handlerCustom = new Handler(mHandlerThread.getLooper()); 
    

    You can attach many handlers to a looper, the handlers are not the problem. The problem is the code that they post. You can post a delayed code that will be executed in a future time, and that code touches some UI elements of a fragment or access context of a fragment. The problem comes when the fragment's view and context is destroyed before the posted code has been executed.