Medium scala functional-programming

How do immutability and actors remove most classic concurrency problems?

The 30 second answer

A race condition needs two things: shared state and at least one writer. Immutability removes the writer, because a value that never changes can be read by any number of threads without a lock. Actors remove the sharing: state lives inside one actor, which handles one message at a time. Locks then become rare. Ordering, blocking and back-pressure problems remain, so you still have to design for those.

Immutable values. The Oracle Java tutorial puts it plainly: immutable objects cannot change state, so they cannot be corrupted by thread interference or observed in an inconsistent state. If every value a thread can see is immutable, there is nothing to lock. To "update", you build a new value and publish it, for example through an AtomicReference or by sending it in a message.

Actors. An actor owns its state and talks to the world only through messages. The Akka documentation notes that an actor needs no synchronized or AtomicInteger for its state, because an actor instance processes one message at a time. Different actors run concurrently, so the system still uses every core.

Here is a tiny actor that owns a price list. The state is an immutable Map; each SetPrice produces the next behavior with a new map.

import org.apache.pekko.actor.typed.{ActorRef, ActorSystem, Behavior}
import org.apache.pekko.actor.typed.scaladsl.Behaviors

object PriceBook:
  sealed trait Command
  final case class SetPrice(sku: String, cents: Long) extends Command
  final case class GetPrice(sku: String, replyTo: ActorRef[String]) extends Command

  // The state is an immutable Map passed to the next behavior. Only this actor sees it,
  // and it handles one message at a time, so there is no lock and no race.
  def apply(prices: Map[String, Long]): Behavior[Command] =
    Behaviors.receiveMessage {
      case SetPrice(sku, cents) =>
        apply(prices.updated(sku, cents))            // next state = new Map
      case GetPrice(sku, replyTo) =>
        replyTo ! s"$sku -> ${prices.get(sku)}"
        Behaviors.same
    }

@main def runPriceBook(): Unit =
  val root = Behaviors.setup[String] { ctx =>
    val book = ctx.spawn(PriceBook(Map.empty), "price-book")
    book ! PriceBook.SetPrice("shoe", 5000)
    book ! PriceBook.SetPrice("shoe", 4500)
    book ! PriceBook.GetPrice("shoe", ctx.self)       // messages from one sender arrive in order
    Behaviors.receiveMessage { reply =>
      println(reply)                                  // shoe -> Some(4500)
      Behaviors.stopped
    }
  }
  ActorSystem(root, "demo")

Verified with Scala 3.3.4 and Apache Pekko 1.1.5 (the Apache-licensed fork of Akka, whose typed actor API mirrors Akka's under the org.apache.pekko package): it prints shoe -> Some(4500).

What it does not solve. In an interview, show you know the limits:

  • Ordering across senders. Messages from one sender to one actor keep their order, but messages from different senders can interleave.
  • Blocking. A blocking call inside an actor or a Future ties up a shared thread pool and can stall the whole system.
  • Deadlock-like waits. Two actors that each wait for the other's reply can still get stuck, just without a lock.
  • Overload. A slow actor's mailbox can grow without limit. That is why Zalando's 2019 post is about back-pressure for an Akka cluster.
  • Mutable objects in messages. Sending a mutable Java list in a message quietly brings back shared state.
Sources (4)
  1. Oracle Java tutorial: Immutable objectsdocs.oracle.com
  2. Akka docs: Introduction to actorsdoc.akka.io
  3. Apache Pekko guide: How the actor model meets the needs of modern systemspekko.apache.org
  4. Zalando Engineering: Back-pressure strategy for a sharded Akka cluster (2019)engineering.zalando.com