When we launch an application in Android, it creates the first thread which is known as the “main” thread and it is manage dispatching of events to the appropriate user interface widgets and communication with components from the Android UI toolkit.

To keep our application responsive, it is necessary to avoid using the main thread to perform any long running operation like Network operations and database calls that may end up keeping it freeze. Android gives us many ways of creating and managing threads, and many other third-party libraries that help us to make thread management very easily.

In this article, you will go through  some common scenarios in Android development where use of threading becomes essential and some simple solutions that can be useful to those scenarios and more.

Introduction

There is a need for mostly Android developer, at some point to work with threads in their application. A thread is simply do small amount work it can’t perform long running task By default but as a thread dies after doing some work, to keep it alive we need to have some sort of loop running on the thread. But we should know when to terminate them when required.

Thread Classes provided by Android

As we know that when an application is launched, it creates a thread of execution for that application which is known as the main thread or UI thread. The main thread also known as a handler thread. The responsibility of main thread is to handling events from all over the app.

If we are executing any block of code that needs to be run into main thread, as we know main thread does so much work than it is better to use any other thread to perform that task. SO that our application will work fine and avoid ANR(application not responding).

For that Android provides many ways of creating and managing threads, and many other third-party libraries that help us to make thread management very easily. Each threaded class is considered for a specific purpose; however, picking the right one that fit to our needs is very important.

  • AsyncTask
  • HandlerThread 
  • ThreadPoolExecutor 
  • IntentService

AsyncTask

AsyncTask make use of UI thread vey easy. AsyncTask allows you to perform background operations and update results on the UI thread without the use of threads or handlers.AsyncTask is used for short operations if you want to perform long running operations then you should go with various APIs which is provided by the java.util.concurrent package, such as Executor, ThreadPoolExecutor, and FutureTask.

AsyncTask have various methods given below:-

1. onPreExecute(): It invoked on the UI thread before the task is executed and this step is normally used to do something before the task gets started — for example, it will simply showing a progress dialog in the user interface.

2. doInBackground(Params…): It invoked on the background thread after the execution of onPreExecute(). This step is used to perform background task that can take a long time. The parameters of the asynchronous task are need to be passed to this step. The result of the execution must be returned by this step, and  sends the result to the onPostExecute().

3. onProgressUpdate(Progress…): It invoked on the UI thread after a call to publishProgress(..). This method is used to show any form of progress in the user interface while the background computation is still executing. For example, it can be used to animate a progress bar or show logs in a text field.

4. onPostExecute(Result): It Invoked on the UI thread after the background implementation finishes. The result of the background implementation is passed to this step as a parameter.

private class AsyncTaskRunner extends AsyncTask<String, String, String> {
@Override  protected void onPreExecute() {
  progressDialog.show();
 }
@Override  protected String doInBackground(String... params) {          . doSomething();
  publishProgress("Sleeping..."); // Calls onProgressUpdate()
  return resp;
 }
@Override   protected void onPostExecute(String result) {
  // execution of result of Long time consuming operation            . progressDialog.dismiss();
  updateUIWithResult() ;
 }
@Override  protected void onProgressUpdate(String... text) {
 updateProgressUI();
 }
}

HandlerThread

A handler thread class is a subclass of the Java thread class. A handler thread is a long-running thread that take work from the queue and operates on it. It’s a combination of other Android primitives, namely:

Looper: It keeps the thread alive and carry the message queue

MessageQueue: It contain the list of messages that to be dispatched by a Looper

Handler: It allows us to send and process message objects which is associated with a thread’s MessageQueue

This simply means that we can keep it running in the background and assign it with more and more task of work sequentially one after the other until we want to quit it. As HandlerThreads run outside of your activity’s life cycle, so they need to be cleaned up properly or else you’ll have thread leaks.

We can create handler threads:-.Create a new handler thread, and create the looper. Now, create a new handler and assign it the looper of the created handler thread and post your tasks on this handler. Other is

HandlerThread handlerThread = new HandlerThread("TesHandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);
handler.post(new Runnable(){…});

ThreadPoolExecutor

What is ThreadPoolExecutor?

A ThreadPoolExecutor is a class which extends AbstractExecutorService. ThreadPoolExecutor takes care of all the threads like assigning task to the thread, keep them alive, termination of thread etc. Whenever a thread in the pool becomes free or available, a task is assigned to a thread from the work queue.


ThreadPoolExecutor(
   int corePoolSize,    // It will initial pool size
   int maximumPoolSize, // Maximum size of pool
   long keepAliveTime,  // Idle time of thread waits before terminating
   TimeUnit unit        // It will sets the Time Unit for keepAliveTime
   BlockingQueue<Runnable> workQueue)  // Queue Work

What are these parameters?

corePoolSize: It help to keep minimum number of threads in the pool. At the initial time, there are no threads in the pool. But as tasks are assign to the queue, new threads will create. If some of them corePoolSize threads are running, the Executor always prefers to add a new thread instead of then queuing.

maximumPoolSize: It allows maximum number of threads in the pool. If this crossed the corePoolSize and the current number of threads is >= corePoolSize, then new worker threads will be created only if the queue is full.

keepAliveTime: If we have number of thread more that thane the core, the noncore threads will wait for a new task. They will be terminated if they don’t get one within the time defined by this parameter.

unit: The unit of time used for keepAliveTime.

workQueue: This is the task queue, which have only hold runnable tasks.

What is a thread pool?

We can consider s thread pool like a pool of threads waiting to be given a task and these assigned task will run in parallel. While running our task in parallel we have to make sure that our code must be thread safe. A thread pool mainly focus on two problems:

  • It help in improved performance when executing a large collection of asynchronous tasks due to reduced per-task overhead.
  • A means of bounding and managing resources when executing a collection of tasks

Runnable

It’s a sequence of instruction which is executed by a thread. 

Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        // Do some work
    }
};

Executor

An Executor is a type of interface which is used to decouple task submission from task execution. Executor mExecutor = Executors.newSingleThreadExecutor(); mExecutor.execute(mRunnable);

ExecutorService

An Executor that manages asynchronous tasks.

ExecutorService mExecutorService = Executors.newFixedThreadPool(10); mExecutorService.execute(mRunnable);

IntentService

IntentService is a subclass which is inherited from Service. To know about IntentService, you should go through with Service. IntentService is started the same way as a normal Service start in android. It uses onHandleIntent() to handles each intent, instead of onStartCommand().It uses a worker thread and stops itself when it runs out of work. To work with it, we have to extend IntentService and implement onHandleIntent().

You may also like...

0 Comments

No Comment.