Book Image

Concurrent Patterns and Best Practices

By : Atul S. Khot
Book Image

Concurrent Patterns and Best Practices

By: Atul S. Khot

Overview of this book

Selecting the correct concurrency architecture has a significant impact on the design and performance of your applications. Concurrent design patterns help you understand the different characteristics of parallel architecture to make your code faster and more efficient. This book will help Java developers take a hands-on approach to building scalable and distributed apps by following step-by-step explanations of essential concepts and practical examples. You’ll begin with basic concurrency concepts and delve into the patterns used for explicit locking, lock-free programming, futures, and actors. You’ll explore coding with multithreading design patterns, including master, slave, leader, follower, and map-reduce, and then move on to solve problems using synchronizer patterns. You'll even discover the rationale for these patterns in distributed and parallel applications, and understand how future composition, immutability, and the monadic flow help you create more robust code. By the end of the book, you’ll be able to use concurrent design patterns to build high performance applications confidently.
Table of Contents (14 chapters)

Countdown latch


A latch is yet another synchronizer. It acts as a gate—threads wait for the gate to open; once the gate— that is—the latch opens, all threads enter it:

Why do we need latches? A latch is used to ensure that, unless some essential, precursor activity has happened, other activities wait for it. Let's look at a real-life example:

The preceding diagram shows how running a race happens on a nice evening. All the players need to assemble at the starting point and wait for the whistle to blow. Once the whistle goes, the players start running, and the race starts.

The starting point is the place of rendezvous: everyone needs to come and wait there for the important activity of the whistle blowing. We can't even imagine a race without it!

So, the runners are threads, the whistle being blown is a one-time activity, such as initialization, and the goal post is, again, an application-specific goal each thread is trying to complete.  

The following code shows the latch in action:

import java...