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)

The lock striping design pattern


What is the problem with the resizing strategy? It hurts concurrency. We have actually reduced the affair to a strictly sequential execution, which is a bottleneck. As a goal, we should strive for allowing more concurrency threads to work on the hash set, which still ensures thread safety!

The following diagram shows two concurrent adds. As both the threads work on separate shared mutable states, we could allow both of them the access:

Two (or more) threads could be adding elements to different buckets, while at the same time other threads could be searching the hash set. 

The lock striping pattern allows us to do just that. The following diagram shows how the pattern works:

Instead of a single lock, we maintain an array of locks. The following code shows the algorithm:

x <- compute the hash for the element
lock(x % length of locks array) // 5 for the above diagram
insert the element for the list at (x % length of table) // 10 for the above

The following is...