Background Execution in a Thread Pool

If your application needs to perform frequent background task execution then creating a new thread every time can be very CPU intensive. The solution here is to use a pool of threads and keep using them.

In iOS, Grand Central Dispatch gives you thread pooling. The system maintains a separate pool for different priorities. Most of the time you will need to use the pool with default priority. Example code:

- (void) someEventHandler {
    dispatch_async(dispatch_get_global_queue(
        DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            @autoreleasepool {
                NSLog(@"Starting short background work");
	        //...
            }        
    });
}

Don’t forget to create a new auto release pool for the task.

In Android, use the concurrency API (instead of AsyncTask which creates a new thread every time. Edit: Well, this is not true. Please read a latter post). For example:

public class MainActivity extends Activity {
    ExecutorService threadPool;

    public void onCreate(Bundle state) {
        threadPool = Executors.newCachedThreadPool();
    }

    void someEventHandler() {
        threadPool.execute(new Runnable() {
            public void run() {
                //Start short background work
            }
        });
    }
}
Advertisements