Recently I was attending a really interesting presentation by Adam Bien who was using Future as part of his demo application. Future offers a very elegant way to implement parallel execution of tasks in Java. As I found the concept quite interesting I thought I give it a try in some pure sample class. And as I did so I thought I could as well write a short blog post at the same time, so here we go.
This is technical stuff, so let’s start with the sample class right away:
The algorithm (not sure I should call it an algorithm ;)) implemented here is checking how many numbers in a given range can be divided by a certain divisor without remainder. Please keep in mind that this is just a stupid example you could as well calculate something here that tells us why 42 is the Answer to the Ultimate Question of Life, the Universe, and Everything . I personally thought I stick to the more trivial problems for the time being.
The main-method is just used to call the two different methods calculating this number and taking the time needed for execution. The first method amountOfDivisibleBy is trivial and does not need any further explanation here. The second method amountOfDivisibleByFuture is where things are getting interesting.
First of all we are getting ourselves an Executor here that is used to start the Future-tasks later on, as well as a list in which we will be storing these tasks:
For the sake of keeping this example simple then two Future-instances are created exactly the same way, added to the list and executed usind the Executor. And this is the nice thing about this. I now have an object (to be precise two objects) that represents the execution of my algorithm.
On these objects I have now different ways on checking if the processing has finished already. In this example it makes sense to go for the “blocking call” using “get” on my Future-objects in a loop. This will only return once the processing is finished, thus in this example the first call will probably wait longer and when I reach the second object processing will be done already and the result is returned. Then the results are simply aggregated and returned at the end of the method.
Indeed it can be seen that execution time of the method using Future is almost twice as fast as the purely sequential execution.
Result : 666666667 calculated in 12500 ms
Result (Future): 666666667 calculated in 6922 ms
As often in these kind of articles this is of course a somewhat artificial example, but I hope it shows quite well how nicely Future can be used to execute tasks in parallel in Java. And maybe there is some real life example of parallel processing just around the next corner sitting there and waiting to get solved using this.
Blog author
Thomas Jaspers
Senior Software Engineer & AI Enthusiast
Do you still have questions? Just send me a message.
Do you still have questions? Just send me a message.