Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java concurrency with thread gates

Manage concurrent thread execution in complex business applications

  • Print
  • Feedback

Page 6 of 6

Listing 11. Prime number consumer

@Override
public void run() 
{
    BigInteger nextVal=null;
        
    do
    {
        nextVal = source.nextPrime();
        if (nextVal!=null)
            System.out.println(nextVal + ", ");
        else break;
    }while (true);
}

In the JUnit 4 test case, several instances of this class are used to simulate the effect of multiple client threads queuing at the thread gate.

A test unit

A JUnit 4 test named com.javaworld.primefinder.PrimeFinderTest is provided in the test folder of the source archive that accompanies this article. The test creates an instance of a GatedPimeNumberSearcher to search for the prime numbers between 1 and a suitable upper bound (e.g., 100, 1 million, 1 thousand trillion); it also creates several reader threads to print out the resulting numbers to system out. You should adjust the upper bound of the search space to suit the capability of your computer, then run the test to watch your thread gate in action!

In conclusion

This article has introduced the concept of thread gates and demonstrated how to implement and use a basic gate class. It has provided source examples and companion source code to enable the reader to explore the idea further. For more on the threading issues raised here, you should read the excellent book Java Concurrency in Practice, written by Brian Goetz and others, along with the other material presented in the Resources section below.

About the author

Obi Ezechukwu is a quantitative Java and Java EE developer working in the UK financial industry. He specializes in designing and implementing real-time and computationally intensive quantitative financial models. He is currently vice president of bond analytics at Markit and co-founder of the obix-configuration project. He holds a Ph.D. in the field of computational finance from Imperial College London.

Read more about Core Java in JavaWorld's Core Java section.

  • Print
  • Feedback

Resources

More from JavaWorld