Tuesday, 31 March 2015

Android Concurrent Programming

Here is a short summary of available options for concurrent programming in Android

AsyncTask<> - useful for a short-lived task that has UI interactivity. The work is done in the doInBackground method, and there are methods for pre and post-task that will execute on the UI thread. This option should not be used for long running operations lasting more than a few seconds as it could be terminated by the system.

Background threads - Manually created. You can choose between an explicitly created thread and one from a thread pool. A background thread may still be terminated by the operating system before it finishes. Useful for operations from 100ms up to a few seconds.
The thread class has to be passed an implementation of the Runnable interface and Thread.Start is called.

Future - a representation of a value that has not yet been computed. The example below creates a future and starts the work. Other tasks are performed in the background. However the calling thread is then blocked as the future's get method is called and the caller awaits the result. (Of course the result may already be available at this point and so the caller is not blocked in this situation).

Future future = executor.submit(new Callable() {
         public String call() {
             return searcher.search(target);
         }});

displayOtherThings(); // do other things while searching

try {
       displayText(future.get()); // use future (will block the caller)
}
catch (ExecutionException ex) { 
       cleanup(); 
       return; 
}


FutureTask - an implementation of a future. It implements the Runnable interface and so may be executed by an executor.

FutureTask future = new FutureTask(new Callable() {
     public String call() {
       return searcher.search(target);
   });
 executor.execute(future);}
 
Some useful slides detailing a lot more techniques are here.

No comments:

Post a comment