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)

Immutability


Immutable objects are thread-safe. When an object is immutable, you cannot make changes to the object. Many threads can read the object at the same time and when a thread needs to change a value, it creates a modified copyFor example, Java strings are immutable. Consider the following code snippet: 

import java.util.HashSet;
import java.util.Set;

public class StringsAreImmutable {
public static void main(String[] args) {
    String s = "Hi friends!";
    s.toUpperCase();
    System.out.println(s);

    String s1 = s.toUpperCase();
    System.out.println(s1);

    String s2 = s1;
    String s3 = s1;
    String s4 = s1;

    Set set = new HashSet<String>();
    set.add(s);
    set.add(s1);
    set.add(s2);
    set.add(s3);

    System.out.println(set);
  }
}

Running the code gives the following output:

Hi friends!
 HI FRIENDS!
 [Hi friends!, HI FRIENDS!]

When we invoke the toUpperCase()method  on the string variable s, as the output shows, there is no mutation happening in...