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)


If a thread blocks, for example, a thread waiting for an I/O operation to complete, this is wasteful. The following diagram shows a thread using a blocking API call for getting a response from a web service over the network. The sequential execution model needs to wait as the flow cannot proceed otherwise.  On the other hand, asynchronous execution does not block the calling thread. A future is used for expressing such asynchronous computations. The following diagram shows how it works:             


As shown, a future is a placeholder. It will eventually contain the response or can timeout if the call takes too long to complete.

How does the calling thread work with the future though? 

The apply method

A future is a trait in the scala.concurrent package, which has an accompanying companion object. This companion provides the apply method, the signature of which is as follows:

       def apply[T](body: => T)(implicit executor: ExecutionContext): Future[T]

The body: => T syntax is...