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)

Our own reentrant lock


The following code shows how we could implement the reentrant lock ourselves. The code shows the reentrancy semantics, too. We just show the lock and unlock method:

public class YetAnotherReentrantLock {
private Thread lockedBy = null;
private int lockCount = 0;

The class has two fields—a lockedBy thread reference and a lockcount—which are used to track how many times the thread recursively locked itself:

private boolean isLocked() {
return lockedBy != null;
}

private boolean isLockedByMe() {
return Thread.currentThread() == lockedBy;
}

The preceding snippet shows two helper methods. Using such helpers help make the code more readable:

public synchronized void lock() throws InterruptedException {
while (isLocked() && !isLockedByMe()) {
this.wait();
 }
lockedBy = Thread.currentThread();
lockCount++;
}

Here is a pictorial analysis of the lock() method:

Keep in mind the lock semantics—the lock is granted if and only if it's in a released state! Otherwise, some other...