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)

Counting semaphores


Concurrent applications usually have a pool of resources. For example, we have thread pooling and connection pooling. Creating and destroying such a connection as we go is costly. Instead, a pool is created, and whenever the app needs a resource, it goes and asks the pool.

The pool is configured to hold a certain number of these resources. For example, 20 database connections or 355 threads. When the demand is high, the pool could get exhausted. Unless some resources are released, the requesting thread should be put to sleep:

A semaphore would come, handy in implementing such scenarios. The semaphore is initialized with an initial capacity, cap, representing the configured pool size:

The following listing shows a semaphore implementation:

public class Semaphore {
 private final int cap;
 private int count;
 private final Lock lck;
 private final Condition condition;

public Semaphore(int cap) {
this.cap = cap;
count = 0;
lck = new ReentrantLock();
condition = lck.newCondition...