Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Concurrency and Futures

Threads, Synchronization and Atomics in Scala

Use JVM threads from Scala: Thread, executors, race conditions, synchronized, volatile, AtomicInteger, concurrent collections, deadlocks and virtual threads.

Scala runs on the JVM and uses the same threads as Java. A Future is built on thread pools, and actor libraries and effect systems sit on top of them too. Understanding the foundations explains why immutability and message passing are so popular: when several threads touch the same mutable data, things break in surprising ways.

This lesson covers the low-level tools you might still need: threads, locks and atomic variables. It also shows the failure modes, so you can recognize them.

Creating threads

SCALA
val t = new Thread(() => println(s"hello from ${Thread.currentThread().getName}"))
t.start()    // runs the lambda on a new thread
t.join()     // wait until it finishes

start() begins execution concurrently; join() waits for it. A Thread is a heavy resource (an operating system thread with a stack of about a megabyte), so applications use thread pools instead of creating threads by hand:

SCALA
import java.util.concurrent.Executors

val pool = Executors.newFixedThreadPool(4)
for i <- 1 to 4 do
  pool.submit(new Runnable { def run(): Unit = println(s"task $i") })

pool.shutdown()   // stop accepting work; already submitted tasks still run

An ExecutionContext for Future can be created from a pool: ExecutionContext.fromExecutor(pool). Always shutdown() pools that you create, or the JVM will not exit.

Since Java 21 there are also virtual threads: very cheap threads managed by the JVM, which make it practical to use one thread per task, even for blocking I/O. In Scala you call them like Java does: Thread.ofVirtual().start(() => ...) or Executors.newVirtualThreadPerTaskExecutor().

The race condition

The classic bug: two threads increment the same counter.

SCALA
var count = 0
val inc = new Runnable { def run(): Unit = for _ <- 1 to 100_000 do count += 1 }

val t1 = new Thread(inc); val t2 = new Thread(inc)
t1.start(); t2.start(); t1.join(); t2.join()
println(count)   // usually LESS than 200000, and different on every run

count += 1 looks like one step but is three: read, add, write. If both threads read the same value before either writes, one update is lost. This is a race condition: the outcome depends on timing. It rarely shows up in tests and often shows up in production.

Why shared mutable state hurts

Read Thread A reads 5.
Read Thread B also reads 5.
Write Both write 6. One update is lost.
1 / 2

Locks: synchronized

Every JVM object has a lock. synchronized lets only one thread at a time run the guarded block for that object:

SCALA
class Counter:
  private var n = 0
  def increment(): Unit = this.synchronized { n += 1 }
  def value: Int = this.synchronized(n)

val counter = Counter()
val workers = (1 to 4).map(_ => new Thread(() => for _ <- 1 to 50_000 do counter.increment()))
workers.foreach(_.start())
workers.foreach(_.join())
println(counter.value)   // 200000, always

Guard every access (reads too), and use the same lock object for the same data. Keep synchronized blocks short, and never call unknown code (callbacks) while holding a lock.

In Scala a synchronized call is a method of every object, so you write this.synchronized { ... } or lock.synchronized { ... } with a private val lock = new Object. There is no synchronized keyword on method declarations as in Java; use the block form.

Visibility: volatile

Even a simple flag may not be seen by another thread, because each thread may cache values. A field marked @volatile is always read from and written to main memory:

SCALA
class Worker:
  @volatile private var running = true
  def stop(): Unit = running = false
  def loop(): Unit = while running do Thread.sleep(10)

@volatile guarantees visibility, not atomicity: running = !running or n += 1 on a volatile are still races.

Atomic variables

For single values, java.util.concurrent.atomic gives lock-free operations that are both visible and atomic:

SCALA
import java.util.concurrent.atomic.AtomicInteger

val hits = AtomicInteger(0)
val threads = (1 to 4).map(_ => new Thread(() => for _ <- 1 to 50_000 do hits.incrementAndGet()))
threads.foreach(_.start()); threads.foreach(_.join())
println(hits.get())   // 200000

Useful methods: incrementAndGet, getAndAdd, compareAndSet(expected, new) and updateAndGet(f), where f must be free of side effects, as it may be retried. AtomicReference[A] does the same for objects and works well with immutable values (replace the whole value atomically).

Concurrent collections

Do not share mutable.Map or ArrayBuffer between threads. Use the Java concurrent collections, or better, immutable data in an AtomicReference:

SCALA
import java.util.concurrent.ConcurrentHashMap

val wordCounts = ConcurrentHashMap[String, Int]()
wordCounts.merge("scala", 1, _ + _)    // atomic update per key
wordCounts.merge("scala", 1, _ + _)
println(wordCounts.get("scala"))       // 2

merge and compute make read-modify-write on one key atomic, whereas a separate get followed by put would race.

Deadlock

If thread A holds lock 1 and waits for lock 2 while thread B holds lock 2 and waits for lock 1, both wait forever. Avoid it by always acquiring locks in the same global order, holding as few locks as possible, and using timeouts (ReentrantLock.tryLock(time, unit)) where a lock is truly needed.

flowchart LR
    A["Thread A holds lock 1"] -->|waits for| L2["lock 2"]
    B["Thread B holds lock 2"] -->|waits for| L1["lock 1"]
    L2 -.held by.-> B
    L1 -.held by.-> A

Parallel collections

Scala 2.13 moved parallel collections into a separate module (org.scala-lang.modules:scala-parallel-collections). After adding it, .par turns a collection into one whose map, filter, reduce and so on run on several threads:

SCALA
import scala.collection.parallel.CollectionConverters.*

val total = (1 to 1_000_000).par.map(_.toLong * 2).sum

Parallel collections help only for pure, CPU-heavy functions over large collections. Operations must be associative for reduce, and side effects inside them are a race condition waiting to happen.

Threads in Java and Kotlin

The three examples below are not Scala but show exactly the same JVM facilities: threads, synchronized and atomics. All results are deterministic.

Java Java: synchronized and AtomicInteger give exact totals (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Kotlin Kotlin: thread pool and ConcurrentHashMap.merge (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Sharing a plain var or mutable collection between threads without any protection.
  • Using @volatile for compound actions such as increments.
  • Forgetting shutdown() on a pool, which keeps the program alive.
  • Locking on a public object (like this of a class others can lock too) or on a string literal.
  • Doing blocking I/O inside synchronized, which stalls every other thread waiting for the lock.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can count += 1 lose updates when two threads run it?

    The steps are not atomic. Both threads can read the same old value and write the same new value, losing one increment.
  2. 2. What does @volatile guarantee?

    Volatile ensures visibility (and ordering) but not atomicity of compound actions.
  3. 3. Which is the correct way to count safely with several threads without a lock?

    AtomicInteger performs atomic, lock-free updates and makes them visible to all threads.
  4. 4. How do you avoid the classic two-lock deadlock?

    A consistent global lock order prevents the circular wait that causes deadlock.

Summary

  • Scala threads are JVM threads; use pools or virtual threads instead of hand-made threads.
  • Shared mutable state causes race conditions; fix it with immutability, synchronized, atomics or concurrent collections.
  • @volatile gives visibility only; AtomicInteger/AtomicReference give atomic updates for single values.
  • Avoid deadlocks with a fixed lock order and short critical sections.
  • Often the best fix is to avoid sharing: use futures with immutable values or message passing.

Next: Actors and Effect Systems