Handler vs AsyncTask vs Thread [closed]

Thread:

You can use the new Thread for long-running background tasks without impacting UI Thread. From java Thread, you can’t update UI Thread.

Since normal Thread is not much useful for Android architecture, helper classes for threading have been introduced.

You can find answers to your queries in Threading performance documentation page.

Handler:

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue.

There are two main uses for a Handler:

  1. To schedule messages and runnables to be executed as some point in the future;

  2. To enqueue an action to be performed on a different thread than your own.

AsyncTask:

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Drawbacks:

  1. By default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. Due to this reason, use AsyncTask to handle work items shorter than 5ms in duration.

  2. AsyncTask objects are also the most common offenders for implicit-reference issues. AsyncTask objects present risks related to explicit references, as well.

HandlerThread:

You may need a more traditional approach to executing a block of work on a long-running thread (unlike AsyncTask, which should be used for 5ms workload), and some ability to manage that workflow manually. A handler thread is effectively a long-running thread that grabs work from a queue and operates on it.

ThreadPoolExecutor:

This class manages the creation of a group of threads, sets their priorities, and manages how work is distributed among those threads. As workload increases or decreases, the class spins up or destroys more threads to adjust to the workload.

If the workload is more and single HandlerThread is not suffice, you can go for ThreadPoolExecutor

However I would like to have a socket connection run in service. Should this be run in a handler or a thread, or even an AsyncTask? UI interaction is not necessary at all. Does it make a difference in terms of performance which I use?

Since UI interaction is not required, you may not go for AsyncTask. Normal threads are not much useful and hence HandlerThread is the best option. Since you have to maintain socket connection, Handler on the main thread is not useful at all. Create a HandlerThread and get a Handler from the looper of HandlerThread.

 HandlerThread handlerThread = new HandlerThread("SocketOperation");
 handlerThread.start();
 Handler requestHandler = new Handler(handlerThread.getLooper());
 requestHandler.post(myRunnable); // where myRunnable is your Runnable object. 

If you want to communicate back to UI thread, you can use one more Handler to process response.

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            //txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this,
                    "Foreground task is completed:"+(String)msg.obj,
                    Toast.LENGTH_LONG)
                    .show();
        }
    };

in your Runnable, you can add

responseHandler.sendMessage(msg);

More details about implementation can be found here:

Android: Toast in a thread

Leave a Comment