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)

Active objects


Here is a classic problem given a piece of legacy code written without any threading consideration. How do we make it thread-safe?

The following class illustrates this problem:

private class LegacyCode {
int x;
int y;

public LegacyCode(int x, int y) {
this.x = x;
this.y = y;
    }
    // setters and getters are skipped
    // they are there though 

There are two methods, m1() and m2(), which change the instance state in some way. Here is the m1() method:

public void m1() {
  setX(9);
  setY(0);
}

It sets the x field to 9 and the y field to 0:

public void m2() {
  setY(0);
  setX(9);
}

 The m2() method does the opposite: it sets x to 0 and y to 9

If we try to make this class concurrent, using threads, you know we need to carefully synchronize access to all shared states.  Of course, any legacy code has many other ramifications—side effects, exceptions, shared data structures, and so on.

It would indeed be a herculean effort to correctly synchronize all the changes. This is a case...