Concurrency and async · Part 24 of 36

Patterns for safe concurrency

Expert 17 min

Message passing, actors, immutable data, thread pools, virtual threads and choosing the right model for a job.

What you will learn

  • You can choose between processes, threads, async and workers for a task.
  • You can apply message passing, immutability and pools.
  • You can explain virtual threads and back-pressure.

Before this: Threads, data races and locks

Share by communicating

The Go community has a famous saying: "Do not communicate by sharing memory; instead, share memory by communicating." Instead of several threads locking the same data, each piece of data has one owner, and others send it messages.

  • Channels (Go, Rust's std::sync::mpsc, Python's queue.Queue) are thread-safe pipes: producers put items in, consumers take them out.
  • The actor model (Erlang/Elixir, Akka) makes every actor a tiny process with private state and a mailbox; it handles one message at a time, so its state needs no locks.
  • Web Workers and postMessage follow the same idea.

Message passing turns the hard question "who may touch this data when?" into a simple one: "who owns it?".

Several conveyor belts feeding one tidy queue

Immutable data

Data that never changes can be shared without any locks. Functional languages lean on this heavily; in JavaScript and Python you get the same benefit by passing frozen/copied data to workers or threads (lesson "Functional programming").

Pools and executors

Creating a thread per task is expensive; a pool keeps a fixed number of workers and feeds them tasks from a queue:

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
with ThreadPoolExecutor(max_workers=8) as pool:      # I/O-bound work
    pages = list(pool.map(download, urls))
with ProcessPoolExecutor() as pool:                   # CPU-bound work (with the GIL)
    results = list(pool.map(render_tile, tiles))

Virtual threads and green threads

OS threads cost memory (often around 1 MB of stack reserved each) and switching between them involves the kernel. Virtual threads (Java 21, September 2023, JEP 444) and goroutines (Go) are lightweight threads scheduled by the runtime onto a few OS threads; you can have millions. They let you write simple blocking-style code ("read, then process, then write") with the scalability of async — an alternative to async/await function colouring.

Back-pressure

If producers create work faster than consumers finish it, queues grow until memory runs out. Back-pressure pushes the limit back to the producer: bounded queues (queue.Queue(maxsize=100)), semaphores that cap in-flight requests, streams that pause reading (Node.js streams, the WHATWG Streams API). Every queue in a production system should have a limit.

Choosing a model

WorkGood fit
Many slow network calls, one machineasync/await (JavaScript, asyncio), virtual threads, goroutines
CPU-heavy number crunching in Pythonprocesses, or free-threaded Python 3.14+, or native libraries (NumPy releases the GIL)
CPU-heavy work in the browserWeb Workers, WebAssembly threads, WebGPU compute
Shared state with complex invariantsone owner + messages (actor), or a database transaction

Testing concurrent code

Races hide from ordinary tests. Tools help: thread sanitizers (TSan for C/C++/Rust/Go, Go's -race flag) detect data races at run time; stress tests run operations millions of times; deterministic simulation testing replays schedules with a fixed seed. Best of all is a design where races can't happen — single ownership, immutability, message passing.

Key points

  • Prefer message passing and single ownership over shared, locked state.
  • Immutable data can be shared freely.
  • Pools/executors reuse threads or processes; use processes for CPU work under a GIL.
  • Virtual threads (Java 21) and goroutines make blocking-style code scale.
  • Bound every queue (back-pressure) and use race detectors and stress tests.

Flashcards

Question: What is the actor model?
Answer: Actors with private state and a mailbox, handling one message at a time — no shared mutable state.
Question: What problem do virtual threads solve?
Answer: They make huge numbers of blocking-style tasks cheap, without async/await.
Question: What is back-pressure?
Answer: Limiting producers when consumers can't keep up, e.g. with bounded queues.
Question: Which tool detects data races in Go programs?
Answer: The race detector (go test -race / go run -race).

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. Which Python executor is the usual choice for CPU-bound work on a standard (GIL) build?

    • ProcessPoolExecutor
    • ThreadPoolExecutor
    • asyncio.gather
    • A while loop
    Show the answer

    ProcessPoolExecutor

    Processes each have their own interpreter and GIL, so they run in parallel.

    Source: Python docs, concurrent.futures

  2. Java virtual threads became a standard feature in which release?

    • Java 21 (2023)
    • Java 8 (2014)
    • Java 11 (2018)
    • Java 17 (2021)
    Show the answer

    Java 21 (2023)

    JEP 444 delivered virtual threads in JDK 21, September 2023.

    Source: JEP 444

  3. Which are forms of back-pressure?

    • A bounded queue that blocks producers when full
    • A semaphore limiting in-flight requests to 10
    • An unbounded list that collects all incoming jobs
    • A stream that pauses reading when the consumer is busy
    Show the answer

    A bounded queue that blocks producers when full; A semaphore limiting in-flight requests to 10; A stream that pauses reading when the consumer is busy

    An unbounded list just grows until memory runs out.

    Source: WHATWG Streams Standard / Python queue docs

  4. "Do not communicate by sharing memory; instead, share memory by ___."

    Show the answer

    communicating

    A Go proverb that summarises message passing.

    Source: The Go Programming Language, Effective Go

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.