Monday, September 09, 2013

ExecutorService and CountDownLatch Example

Image from Jeff Blogs
One of the most difficult concepts in teaching programming is threads. If you don't do a lot of thread programming, that knowledge has a quick way of being replaced in your mind.

Today, modern frameworks especially Java EE make thread programming even less apparent to the developer.

I had a very highly asynchronous application that was generating data based on examining data returned from a measurement sensor in a grain silo. The sensor was generating a lot of data especially as the silo was being filled, or emptied. I had a Java application that was generating real-time data that would start/stop various hardware based on how full, or empty the silo was. This application was also generating data charts. We have one big giant potential mess if the application does not work right. The Java Concurrency API came to the rescue. The charting data could be kicked off using CountDownLatch to ensure that we didn't start generating a new chart until the last chart was generated from the data. The sensor was generating more data than our application could chart in real-time.

In the last year, I have taught a couple of programming courses to our JUG, and invariably I need to cover Thread programming.

This is an example application that shows what happens if threads are left to their own devices. This example "works" sometimes, but usually the counter does not match up correctly with the other counters. You may need to run it a couple of times to "see" it break.

If you have a simple example that demonstrates this concept, please let me know. I am always looking for good ideas.

Here is the project code: ExecutorLatchExample


Popular Posts