design for responsiveness : multi-threading
DESCRIPTION
by Daniel, Dao Quang MinhTRANSCRIPT
Design for Responsiveness : Multi-Threading
Daniel, Dao Quang Minh
Design for Responsiveness
* Evil * Application not
Responding (ANR) Dialog
What triggers ANR ?
No response to an input event (e.g. Key press, screen touch within 5 seconds)
A BroadcastReceiver hasn't finished executing within 10 seconds
How to avoid it ?
How to avoid it ?
Android applications normally run entirely on a single main thread.
Hence anything that takes a long time to complete might trigger the ANR dialog.
How to avoid it
Long running operations and computationally expensive calculations should be done in child threads.
Create a child thread
Handler class allows you to queue tasks to be run on different threads and allows you schedule tasks using Message and Runnable objects
Handler mHandler = new Handler(){
public void handleMessage(Message m){ //a hook that let you pass messages
//do something here when receive messages
}
}
new Thread(){
public void run(){
doStuff();
Message m = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("key","value");
m.setData(b);
mHandler.sendMessage(m); // add Message to the end of the MessageQueue
}
}.start();
Create a child thread
Besides sending messages, we can also send Runnable objects directly and schedule things to be run at different times in the future.
post(Runnable r)
postAtFrontOfQueue(Runnable r)
postAtTime(Runnable r, long uptimeMillis)
Etc.
docs/reference/android/os/Handler.html
Manage > 1 Threads
Executor: an object that executes submitted Runnable tasks. This interface provides a way to decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.
An Executor is normally used instead of explicitly creating threads
docs/reference/java/util/concurrent/Executor.html
Manage > 1 Threads
ExecutorService : a more extensive interface for Executor.
Allows you to manage termination and tracking progress of one or more async tasks.
Demo program
http://www.engineyard.com/blog/2009/programmingcontestwiniphone3gs2kcloudcredit/ sequence of twelve words that when hashed is bit
wise closest to a hash of a challenge phrase All words must be from a 1,000 word dictionary Basically a Hamming distance problem. Let's dive into the code