Concept

Shared State

Definition

Shared state is data that more than one part of a program, especially more than one thread or process, can read and modify. When two units of execution touch the same data without coordination, the result depends on the unpredictable order in which they happen to run.

A common framing is that shared state is incorrect state, because nothing guarantees a consistent view of it. The phrase is a deliberate exaggeration meant to make developers treat shared mutable data with suspicion.

Why it matters

How it works

There are two broad strategies for taming shared state. The first is to protect it: guard every access with locks, semaphores, or transactions so that only one actor touches the data at a time. This works but adds complexity and the risk of deadlock.

The second, often preferable, strategy is to avoid sharing. Favor immutable data that cannot be changed after creation, give each actor its own private state, and have components communicate by passing messages rather than reaching into common memory. Less shared mutable state means less to coordinate and less to get wrong.

Where it goes next

Continue exploring

Tags