In Android development, you can’t execute a task longer than 5 secs on main
thread, so that’s the reason why we need asyncronized task.
Google provided Thread, AsyncTask, Service for developers, I’ll
briefly introduce Thread and AsyncTask in this article. Also, there is
useful mechanism reffered to ReentrantLock. I’ll get to it at the end.
1. Thread
Timing
- Long task in general
- For tasks in parallel
Drawbacks in our app
Because threads can be run in parallel, task like “send message” will result
in “out of sequence response” error. Actually, it can be resolved using
“Reentrant Lock”. We’ll get to it later in the article.
Call this on any thread :
new Thread(){
public void run(){
/* put your methods here */
}
}.start();
if you’d like to update UI, it requires a handler to do the job:
Handler handler = new Handler();
new Thread(){
public void run(){
/* put your methods here */
handler.post(r1); // update UI
}
}
Runnable r1 = new Runnable(){
public void run(){
//update UI methods here
}
};
2. AsyncTask
Timing
- Small task with a lot works regarding to UI thread
- For tasks required to be done serialized rather than parallel
- It can still run tasks in parallel
DrawBacks
- One instance can only be executed once
- Should be created and executed on Main Thread
Implementation:
private class YourTask extends AsyncTask<String, String, Void> {
//automatically execute this function while entering
@Override
protected Void doInBackground(String... params){
/*do your task here*/
publishProgress(params[0]);
//update UI, which would redirect to
//onProgressExecute function
}
@Override
protected Void onProgressExecute(String... params){
/*update UI here*/
}
@Override
protected Void onPostExecute(Void result){
/*execute while task ends*/
}
}
Then, based on your need, make different execution call on UI thread:
If you want your task to be executed sequentially
new YourTask().execute(params);
If you want your task to be executed in parallel
new YourTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
3. ReentrantLock
Timing
While a block of code is being executed, you don’t want another call enter this
block at the same time, which may cause race condition, so before entering this
block, you let it acquire a lock. Then, other attempts to this block should
wait until previous call is completed.
Usage
According to Android Developer document:
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
which means ReentrantLock has similar function to syncronized modifier, but
with stronger features.
You can follow the sample code below:
ReentrantLock lock = new ReentranLock();
public void funtion(){
lock.lock();
try{
//method body
}catch(Exception e){
//deal with exception
}finally{
lock.unlock();
}
}