Java Threading – Callable and Future

I recently was asked to take a technical test for a contract position and the last question had to do with using the Java Callable interface. After the test I created a project to run multiple threads and check each return for the possibility of a perfect number. The first four perfect numbers are 6, 28, 496, and 8128.

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Let’s look at the first perfect number 6, 1+2+3=6. Remember that we don’t use the number itself because it would be a factor as well.

The most accurate information online about perfect numbers can be found here.

I set out to gather some perfect numbers beyond the initial four, which are bold on the OEIS site. The reason they are bold is that most programmers could find these with a simple program in the course of a day, let’s say. My first attempt at the next number, 33,550,336 was a failure initially. I ran a threaded application on an Apple macbook pro for 3 days and stopped it because I was unsure if it would complete. That was my decision and it may have completed on day four. I do believe that my threading strategy was on the right track but I have since found 33,550,336 in about 4 hours using Java’s Callable and Future implementation.

The two classes of importance are shown here for reference.

I am also currently setting up a RabbitMQ high-availability cluster and I see this pattern as a way to load test the cluster. The Future could get a simple message for verification. The implementations of Callable could be a blast of individual threads that represent a mass number of client requests.

You can visit this project on github at https://github.com/dlwhitehurst/concurrent

Leave a Reply

Wow, 3,211 people read this.