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)

Reader or writer locks

A readers–writer(RW) or shared-exclusivelock is a primitive synchronization that allows concurrent access for read-only operations, as well as  exclusive write operations. Multiple threads can read the data concurrently, but for writing or modifying the data, an exclusive lock is needed.

A writer has exclusive access for writing data. Till the current writer is done, other writers and readers will be blocked. There are many cases where data is read more often than it is written.

The following code shows how we use the locks to provide concurrent access to a Java Map<K, V>. The code synchronizes the internal map, using an RW lock:

public class RWMap<K, V> {
private final Map<K, V> map;
private final ReadWriteLock lock = new ReadWriteLock();
private final RWLock r = lock.getRdLock();
private final RWLock w = lock.getWrLock();

public RWMap(Map<K, V> map) { = map;

public V put(K key, V value) throws InterruptedException {