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)

Message driven concurrency

The following listing shows our first actor-based program in action. We show a single actor, living in an actor system and we talk to this actor by sending messages. These messages land in the actor's mailbox and each message is processed sequentially, one at a time:


import{Actor, ActorLogging, ActorSystem, Props}

class MyActor extends Actor {

override def receive: PartialFunction[Any, Unit] = {
case s: String => println(s"<${s}>")
case i: Int => println(i+1)


object MyActor extends App {
def props() = Props(new MyActor)

val actorSystem = ActorSystem("MyActorSystem")

val actor = actorSystem.actorOf(MyActor.props(), name = "MyActor")

actor ! "Hi"
actor ! 34

case class Msg( msgNo: Int)

actor ! Msg(3)

actor ! 35


We have an actor, named MyActor, which lives in an actor system named MyActorSystem. We create the actor and hold its actorReference in the actor variable...