Tuesday, January 14, 2014

Java's CountDownLatch

In our Android phone TV application, we need a few server resources before meaningful data can be fetched. For example, we need to know the template for the playback URL so that when user select a channel, we can construct a full URL to play from the channel ID, the device dimension, etc. We also need to fetch another table that tells us which settings to use when the app is connected to a WiFi spot versus when it's on a cellular signal. We need these and a few other essential resources before the app can start.

All of these resources are asynchronous fetches from the server. And we don't want to navigate to the home page until all resources have been retrieved. A handy class to help track that we've got all those resources is the CountDownLatch. It blocks the calling thread until the count reaches zero. You create the latch, fire off your asynchronous tasks in separate threads. Then when each of the task is finished, you decrement the count by calling countDown().

To block the calling thread, you call the await() method. One mistake I made the first time was call wait() instead of await(), so make sure you call the right method. If you call wait, you'll get an IllegalMonitorException.

Warning: NEVER block the UI/main thread!


It's obvious, but still worth noting. You should not use this on the main thread. Instead I would use this to patch several tasks and make it act like a single operation, then notify the UI that all tasks are done via a handler or broadcast receiver.

To see how it all works, I wrote a simple function and run it to see how it looks:

Sample code



Sample output


01-07 10:50:53.758    7809-7809/com.mobitv.refapp I/System.out﹕ DEMO - execWorkerTasksBlocking <<
01-07 10:50:54.018    7809-8129/com.mobitv.refapp I/System.out﹕ DEMO - Completed: task A
01-07 10:50:54.118    7809-8129/com.mobitv.refapp I/System.out﹕ DEMO - Completed: task C
01-07 10:50:54.269    7809-8130/com.mobitv.refapp I/System.out﹕ DEMO - Completed: task B
01-07 10:50:54.369    7809-8130/com.mobitv.refapp I/System.out﹕ DEMO - Completed: task E
01-07 10:50:54.879    7809-8129/com.mobitv.refapp I/System.out﹕ DEMO - Completed: task D
01-07 10:50:54.879    7809-7809/com.mobitv.refapp I/System.out﹕ DEMO - execWorkerTasksBlocking >>

No comments:

Post a Comment