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)

A future task

A future task is essentially an asynchronous construct. As its name signifies, it is a wrapper for some expensive computation whose result will be available sometime in the future. Once the computation is completed, it returns the result via a get() method call.

       As listed and shown in the figure, the future task have three states:

  1. Waiting to run
  2. Running 
  3. Completed 

When we try to obtain a result from the future task, the behavior depends on which state it is in. If it is not completed yet, the thread calling get() sleeps till the computation is done, and the result is available. There is also an overloaded get(long timeout, TimeUnit unit) method that avoids waiting forever. So, taskget(5L, TimeUnit.SECONDS) would wait for only five seconds. If the method does not return within the time prescribed, a TimeOutException will be thrown.

The following code shows the future task in action: 

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;