6 JDK concurrency libraries

 

This chapter covers

  • Atomic classes
  • Locks classes
  • Concurrent data structures
  • BlockingQueues
  • Futures and CompletableFuture
  • Executors

In this chapter we’ll cover what every well-grounded developer should know about java.util.concurrent and how to use the toolbox of concurrency building blocks it provides. The aim is that by the end of the chapter, you’ll be ready to start applying these libraries and concurrency techniques in your own code.

6.1 Building blocks for modern concurrent applications

As we saw in the previous chapter, Java has supported concurrency since the very beginning. However, with the advent of Java 5 (which was itself over 15 years ago), a new way of thinking about concurrency in Java emerged. This was spearheaded by the package java.util.concurrent, which contained a rich new toolbox for working with multithreaded code.

Note

This toolbox has been enhanced with subsequent versions of Java, but the classes and packages that were introduced with Java 5 still work the same way, and they’re still very valuable to the working developer.

If you (still!) have existing multithreaded code that is based solely on the older (pre-Java 5) approaches, you should consider refactoring it to use java.util.concurrent. In our experience, your code will be improved if you make a conscious effort to port it to the newer APIs—the greater clarity and reliability will be well worth the effort expended to migrate in almost all cases.

6.2 Atomic classes

6.3 Lock classes

6.3.1 Condition objects

6.4 CountDownLatch

6.5 ConcurrentHashMap

6.5.1 Understanding a simplified HashMap

6.5.2 Limitations of Dictionary

6.5.3 Approaches to a concurrent Dictionary

sitemap