0% found this document useful (0 votes)
13 views6 pages

Lesson 9 - Multithreading and Asynchronous Processing in Mobile Applications

Multi threading

Uploaded by

Paul Pogba Clive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Lesson 9 - Multithreading and Asynchronous Processing in Mobile Applications

Multi threading

Uploaded by

Paul Pogba Clive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Multithreading and Asynchronous Processing in Mobile Applications

Introduction to Multithreading and Concurrency in Mobile Applications


In mobile applications, it is very important to perform certain tasks in the background, like fetching
data from a server, saving files, or handling intensive calculations, to keep the app responsive.
Multithreading allows for the running of multiple tasks concurrently thereby improving
performance and user experience by not blocking the main thread (UI thread) where the user
interface is rendered. Let’s take the basic definition of terms first.
1. Thread: A separate path of execution. Every Android app has a main thread (UI thread)
and can spawn additional threads.
2. Concurrency: This is the ability to execute multiple tasks or processes simultaneously.
Specific Objectives:
By the end of the lesson, students should be able to:
1. Demonstrate an understanding about threading and concurrency in mobile applications.
2. Use AsyncTask and WorkManager for background processing.
3. Implement asynchronous API calls to ensure a smooth user experience.

Asynchronous Programming
An asynchronous model allows multiple things to happen at the same time. When your program
calls a long-running function, it doesn’t block the execution flow, and your program continues to
run. When the function finishes, the program knows and gets access to the result (if there’s a need
for that).
Let’s take an example of a program that fetches two files over a network and combines them:
In an asynchronous system, the solution is to start an additional thread of control. The first thread
fetches the first file, and the second thread fetches the second file without waiting for the first
thread to finish, and then both threads wait for their results to come back, after which they
resynchronize to combine their results.
Another example with a single-thread approach is a program that requests a file from the OS and
needs to make a mathematical operation.

1
In an asynchronous system, the program asks the OS for the file and returns the control to the
mathematical operation to be executed on the CPU, while waiting for the file.
One approach to asynchronous programming is to make functions that perform a slow action and
take an extra argument, a callback function. The action is started, and when it finishes, the callback
function is called with the result.

Multithreading Programming
Multithreading refers to the concurrent/parallel execution of more than one sequential set (thread)
of instructions.
On a single processor, multithreading gives the illusion of running in parallel. In reality, the
processor is switching by using a scheduling algorithm. Or, it’s switching based on a combination
of external inputs (interrupts) and how the threads have been prioritized.
On multiple processor cores, threads are truly parallel. Individual microprocessors work together
to achieve the result more efficiently. There is multiple parallel, concurrent tasks happening at
once.
A basic example of multithreading is downloading two files from two different tabs in a web
browser. Each tab uses a new thread to download the requested file. No tab waits for the other one
to finish, they are downloading concurrently.
The following picture shows a simple explanation of concurrent execution of a multithreaded
application:

2
1. Threading and Concurrency in Mobile Applications
Why Multithreading?
The main thread in Android is responsible for rendering the UI and handling user interactions.
When time-consuming operations are performed on the main thread, the application becomes
unresponsive. To avoid this, background threads are used for handling other requests like:
1. Network requests (e.g., downloading data, accessing APIs)
2. File operations (e.g., reading/writing large files)
3. Database operations (e.g., querying or updating large databases)
4. Heavy computations (e.g., image processing, data parsing)
In Android, only the main thread has capacity to modify the UI. However, if we need to perform
background operations, they must be done on separate threads and results should be passed back
to the main thread to update the UI. This separation of UI work from background work helps in
keeping the app responsive.
Simple Approaches to Background Processing in Android Development
1. Use of Java Threads – These are basic threads used for concurrent tasks. However, in
programming, manually managing threads can be a daunting task.
2. Use of Handlers and Runnables – These are used for communicating between the main
and background threads.
3. Use of AsyncTask (deprecated in API level 30): This is a simpler way to handle short-
lived background tasks without manually managing threads. And finally,

3
4. Use of WorkManager: The WorkManager is used for scheduling and managing
background work that needs to be deferrable and guaranteed to execute, even if the app
closes.
In the next couple of lines, look further into the working processes involved in using AsyncTask
and WorkManager.

The AsyncTask
AsyncTask was introduced to simplify the management of background tasks, especially those that
need to communicate results back to the main thread. It includes three basic steps outlined in three
main methods:
1. doInBackground(): This method handles the background task.
2. onPreExecute(): This method runs before the background task starts, usually for setup.
3. onPostExecute(): This method runs after doInBackground() finishes, updating the UI with
results.
AsyncTask Example
private class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Setup code here, e.g., showing a progress bar
}

@Override
protected String doInBackground(String... urls) {
// Simulate downloading data or accessing API
return downloadData(urls[0]);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Update UI with the downloaded result
}
}
Limitations of AsyncTask
While the AsyncTask is useful for short-lived background tasks, it has some serious limitations:
1. Not suitable for long-running tasks (e.g., background music or large file downloads).

4
2. Not lifecycle-aware, meaning it doesn’t automatically handle configuration changes, like
screen rotations.
3. Due to these limitations, it is no longer supported in API 30
Implementing WorkManager for Background Processing
WorkManager presents a flexible and robust way of scheduling tasks that may need to continue
even if the user leaves the app. It is ideal for periodic and one-time background tasks, especially
those that must complete reliably. Let us take a little time to discuss the steps needed in
implementing WorkManager. The first step is to define the work to be done by extending the
worker class and then defining the method that is meant to be executed. Then, the next is to
enqueue the work request, and schedule it to run either once or periodically.
1. Define the Work: Extend Worker to create a task that WorkManager can run in the
background.
public class UploadWorker extends Worker {
public UploadWorker(@NonNull Context context, @NonNull WorkerParameters
params) {
super(context, params);
}

@NonNull
@Override
public Result doWork() {
// Perform the background work here
uploadFile();
return Result.success();
}
}
2. Enqueue the Work Request: Schedule the work to run either once or periodically.
WorkRequest uploadWorkRequest = new
OneTimeWorkRequest.Builder(UploadWorker.class).build();
WorkManager.getInstance(context).enqueue(uploadWorkRequest);
Advantages of WorkManager:
1. Even if the app closes, the task will resume when possible.
2. Allows chaining of tasks, where each depends on the completion of the previous one.
3. You can specify conditions (like network availability or charging state) before executing.

5
Asynchronous vs Multithreading
From the foregone explanations just provided, we can see that multithreading programming is all
about concurrent execution of different functions. Async programming is about non-blocking
execution between functions, and we can apply async with single-threaded or multithreaded
programming. In other words, multithreading is one form of asynchronous programming.
Let’s take a simple analogy; you have a friend, and you decided to make dinner together.
Async is when you say to your friend, “You go to the store and buy pasta. Let me know when you
get back, to make dinner together. Meanwhile, I’ll prepare sauce and drinks.”
Threading is, “You boil the water. I’ll heat the tomato sauce. While the water is boiling, ask me
and I’ll put the pasta in. When the sauce is hot, you can add cheese. When both are done, I’ll sit
down and you serve dinner. Then we eat.”. In the threading analogy, we can see the sequence of
“When, Do” events, which represent the sequential set of instructions per each person (thread).
From that analogy, we can conclude that Multithreading is about workers, Asynchronous is about
tasks.
5. Which One to Use?
Choosing between the two programming models depends mainly on performance.
Given all possible combinations between sync/async and single/multi-threading, which model
should perform better?
In a nutshell, for large scale applications with a lot of I/O operations and different
computations, using asynchronous multithreading programming flow, will utilize the
computation resources, and take care of non-blocking functions. This is the programming
model of any OS!
With more power, comes more responsibility! So if we decided to implement this model, we have
to take care of different issues like race condition, deadlocks, shared resources, and callbacks
events.

You might also like