Java Class for Easy Multithreaded Loops

Dec 16, 2016
By: Marissa Camilli

Java’s great for multithreading, but the setup for ExecutorService, waiting for completion, etc. can be cumbersome and is honestly pretty boilerplate for many situations.  Can’t there be a shortcut?  I love what lambdas in 1.8 did for code brevity; could there be something like that?  I say there should be, so I wrote a class that implements all the boilerplate code and reduces it to sending your loop body via lambda to a static method.  I called the class AQ for “Asynchronous Queue”.  The AQ class is up on GitHub.

For example, check out this code that is just dying to be multithreaded:
for (ComputeObj obj: list) {

This is a really simple example where we have list where each element needs some computing, but the results of each computation don’t depend on each other.  ComputeObj is a fake class used here for demonstration purposes.  (What you do with this can be more complex; there could be a lot going on in that for loop.)

This is the code using AQ:

for (ComputeObj obj: list) {
AQ.add(() -> {

What this is doing is using a lambda to invisibly create a Runnable object and sending it to an ExecutorService object to immediately begin processing.  The finish() method says, “ok finish up all the computations and proceed normally.”

Behind the scenes the AQ object is pretty simple.  When you pass a Runnable into add() AQ checks the calling class and the thread ID of the caller.  Since AQ is static, this check makes sure AQ isn’t accidentally being called from different parts of the code in parallel.  With AQ.finish(), the ExecutorService waits for the processes to finish, then the calling class/thread tracking info is cleared out and the ExecutorService is initialized.

Obviously AQ may not be the best solution for your particular situation; it’s really best for code that is primarily single threaded but that has many process-heavy loops that you’d like to see sped up… and if each iteration of the loop is self-contained, then why not?  Why not have faster code?  YOU DESERVE FASTER CODE!  Check out this ActivityMonitor screenshot of a Java app using the AQ class on a 12-core (24 virtualized) MacPro:


Lit up like a Christmas tree!

Again, the full class can be downloaded here:

So that’s that.  Not rocket science, but hopefully a handy utility method for you.  By the way, Digital Turbine is hiring; in addition to Java there’s a lot of cutting edge Scala, Aerospike, and mobile tech being done. Read more about current job openings and apply here.

Marissa Camilli
By Marissa Camilli
Read more by this author