Use High-Level Concurrency Abstractions

Sometimes (most of the time, actually), you just need to make your program multithreaded. For example, you might have to handle multiple users at the same time in a web application. Or maybe you’ve got a desktop or Android application that interacts with the user and the screen in a UI thread and executes compute-intense tasks in background threads.

In those cases, you’ll typically let your threads communicate via shared memory: one thread writes a variable that another one reads, and vice versa. Java has supported such a built-in threading model and synchronization primitives since its inception. That’s been one of its major advantages in comparison to other high-level languages at the time.

These primitives are keywords like volatile and synchronized, which you can use to mark critical sections in your code. You can also work with threads through the start() and join() methods of the Thread class and use wait() and notify() on any Object to let threads sleep and wake up. These primitives work, and you can build correct multithreaded programs using only them. But they’re also easy to misuse, and they’re tricky if you have special multithreaded requirements, such as fairness.

Concurrency primitives in Java belong to the past. The language has evolved a lot and has undergone many improvements in terms of higher-level classes for writing concurrent code. We recommend that you rely exclusively on these higher-level classes. There’s more of them than we can reasonably cover here, but examples are synchronization classes such as Semaphore, CountDownLatch, or CyclingBarrier and data structures such as AtomicInteger, LongAdder, ConcurrentHashMap, CopyOnWriteArrayList, or BlockingQueue.

To use those classes correctly, you need to have a solid understanding of how the Java Memory Model and the happens-before relations between state changes in that model work. Maybe we’ll write a second book about all of this one day, but if we don’t get around to it, there are several excellent books on the subject out there waiting for you: Java Concurrency in Practice [Goe06], which we’ve mentioned before, and also Programming Concurrency on the JVM [Sub11].

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.76.204