Saturday, March 26, 2011

Multi Threading models in Android

Android has a UI Thread for updating the UI. For any other call like Disk IO or network activity it is recommended to do it in the in a separate thread. Android provides various alternatives to threads which are nice to have as your activities can be killed anytime leaving your thread hanging. But at the same time you need to be careful to use the right one  for your circumstances.

Following are the options available to you

1. java.lang.Thread

This is the standard java thread and it executes in the VM. For most uses its recommended that you do not use it because of synchronization and updating of UI is difficult via such a mechanism.

2. android.app.Service

A service is a mechanism provide by Android to do various tasks in the background. It runs in the main thread, but its can spawn java.lang.Thread and perform various CPU intensive/IO tasks. Not a recommended approach again because its basically yet another thread spawning mechanism in the end. A service generally has higher priority and is the last to be killed in case of low memory.

3. android.os.AsyncTask

AsyncTask is the preferred way to do things in the background and update the UI based on that. It can be achieved in a very direct manner using this mechanism without the hassles of handlers or thread manipulations or synchronization mechanisms.

4. android.app.IntentService

Android proves a special type of service which is called the IntentService. This implements a "work queue processor" pattern, which means at one time a single task is processed here at a time. The service will stop as soon as  all tasks in its queue are completed. It is especially useful in cases where we are not really interested in the result. Something like writing to the DB asynchronously while you have data in the memory always can be offloaded to an IntentService which will queue the requests and update them.

Since there are various means available, finally its upto the developer to evaluate the various options are weigh in the best mechanism for his scenario.

Do write in the comments, your opinion on this.

No comments:

Post a Comment