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 bounded buffer

A bounded buffer is one with a finite capacity. You can only buffer a certain amount of elements in it. When there is no more space left to store the elements, the producer threads putting the elements wait for someone to consume some of the elements.

On the other hand, the consumer threads cannot take elements from an empty buffer. In such cases, the consumer thread will need to wait for someone to insert elements into the buffer.

Here comes the code, which we will explain as we go:

public abstract class Buffer {
private final Integer[] buf;
private int tail;
private int head;
private int cnt;

The elements are stored in an array of integers, buf:

As shown in the preceding diagram, the field tail points to the next empty position to put the element in. In the provided diagram, three elements were inserted and none were taken. The first element to be consumed is 2, which resides at the index 0 of the internal array. This is the index we hold in the head field. The value of count...