Thread safety

Also known as: thread-safe

On this page 7

Thread safety is the property of a function, class or data structure that behaves correctly when multiple threads access it concurrently, regardless of how the scheduler interleaves their operations, and without requiring extra coordination from the caller. In concurrency within programming, a component is called thread-safe when every operation preserves its invariants and produces results that are consistent with some valid sequential order.

The property matters because modern runtimes execute threads in parallel on multiple cores, and unsynchronized access to shared mutable state leads to race conditions, corrupted data structures and failures that appear only under load. Thread safety is not a single technique but a contract: it states which guarantees a component gives and under which usage conditions those guarantees hold.

How thread safety prevents corrupted shared state

Thread safety prevents corruption by ensuring that no thread observes or modifies shared data in an intermediate state. A simple statement such as count++ compiles into a read, a modification and a write; when two threads interleave these steps, one increment is silently lost. This failure is a data race, and in languages such as C, C++ and Rust it is formally undefined behavior rather than merely a wrong number.

Three properties must hold for correct concurrent access. Atomicity guarantees that a compound operation appears indivisible. Visibility guarantees that a write by one thread becomes observable to others, which processor caches and compiler reordering otherwise prevent. Ordering guarantees that operations are seen in a consistent sequence, defined in practice by a language memory model such as the Java Memory Model or the C++11 memory model and its happens-before relation.

The table below summarizes the three properties and the typical defect when each is missing.

PropertyWhat it guaranteesTypical defect when missing
AtomicityCompound updates appear indivisibleLost updates, torn writes
VisibilityWrites reach other threadsThread loops forever on a stale flag
OrderingConsistent sequence of effectsObject seen before construction finishes
Core properties behind thread-safe code

Levels of thread safety guarantees

Thread safety is a spectrum of guarantees, and professional documentation states which level a component offers. A widely used classification distinguishes immutable, unconditionally thread-safe, conditionally thread-safe, thread-compatible and thread-hostile components. Choosing the wrong assumption about this level is one of the most common sources of concurrency bugs in production code.

LevelMeaningTypical example
ImmutableState never changes after constructionString objects in Java and C#
Unconditionally thread-safeAny sequence of calls is safeConcurrent hash maps
Conditionally thread-safeSafe per call, compound actions need lockingSynchronized collection wrappers
Thread-compatibleSafe only with external synchronizationStandard library vectors and lists
Thread-hostileUnsafe even with external lockingCode that mutates global state
Common levels of thread safety

The distinction between per-call safety and compound action safety is decisive. A thread-safe map makes each get and put safe, yet a check-then-act sequence such as testing for a key and then inserting it remains a race unless the map offers an atomic method like putIfAbsent or computeIfAbsent.

Techniques for achieving thread safety

Developers achieve thread safety either by avoiding shared mutable state or by coordinating access to it. The first strategy is usually simpler and faster; the second is unavoidable when threads must cooperate on common data. Most robust designs combine both, keeping the synchronized core small and well documented.

The following table compares the main techniques with their costs and typical uses.

TechniqueHow it worksMain cost or risk
ImmutabilityObjects cannot change after creationAllocation of new copies
Thread confinementData is owned by one thread onlyRequires disciplined handoff
Mutual exclusionA mutex or monitor serializes accessContention, deadlock risk
Atomic operationsHardware instructions such as compare-and-swapHard to compose, ABA problem
Lock-free structuresRetry loops built on atomicsHigh design complexity
Message passingThreads exchange copies through queuesCopying and queue latency
Main techniques and their trade-offs

Thread confinement includes thread-local storage and patterns such as the actor model, where each actor processes its own messages sequentially. Language features also help: Rust enforces thread safety at compile time through its Send and Sync traits, so a data race in safe Rust is rejected by the compiler rather than discovered in testing.

Thread safety overlaps with several neighboring ideas but is not identical to any of them. Reentrancy, for example, concerns whether a function can be safely interrupted and called again, which matters for signal handlers and recursion even in a single thread. A function can be thread-safe through locking yet not reentrant, because a second call from a signal handler would wait forever on its own lock.

ConceptFocusRelation to thread safety
Race conditionOutcome depends on timingThe defect thread safety eliminates
ReentrancySafe re-entry during executionOverlapping but independent property
Atomic operationSingle indivisible stepA building block, not a full solution
Deadlock freedomThreads never block each other foreverA liveness goal beyond correctness
Async safetySafe within an event loopConcerns tasks rather than OS threads
How thread safety relates to neighboring concepts

Correctness alone is not enough. Thread-safe code must also preserve liveness, meaning that it avoids deadlock, livelock and starvation, and it should scale reasonably with core count. A design that wraps everything in one global lock is safe yet often serializes the whole program.

Common mistakes and how to avoid them

Most thread safety defects come from a small set of recurring patterns, and reviewers who know them catch bugs that tests rarely reproduce. Concurrency failures are nondeterministic: a test can pass thousands of times and still hide a race that appears on a different processor or under heavier load.

  • Assuming composition is safe: two thread-safe calls in sequence do not form a thread-safe operation.
  • Double-checked locking without proper memory semantics: publishing an object without a volatile or atomic reference can expose a partially constructed instance.
  • Locking on the wrong object: different threads that lock different instances protect nothing.
  • Inconsistent lock ordering: acquiring locks in different orders produces deadlocks.
  • Leaking internal state: returning a mutable internal collection lets callers bypass synchronization.

Effective verification combines code review, documentation of the guarantee level and dynamic tools such as ThreadSanitizer, which instruments memory accesses to detect data races at runtime. Static analyzers and annotations such as guarded-by markers add a further layer, while stress testing on many cores increases the chance of exposing rare interleavings.

In simple terms

Imagine a shared whiteboard where several people keep a running total. If two people read the number at the same moment, each adds one and writes the result, one of the additions disappears. Thread safety means organizing the work so that never happens, for example by letting only one person hold the marker at a time.

In software, the people are threads and the whiteboard is shared memory. Code is thread-safe when it gives correct results no matter how many threads use it at once or in what order they happen to run.

A practical example

A team runs an online booking service on a server with 16 cores. Each incoming request runs on a thread from a pool, and every request updates an in-memory counter of available seats. The original code reads the counter, checks that it is above zero and then decrements it. Under a promotion with roughly 2,000 requests per second, the service occasionally sold more seats than existed, because two threads read the same value before either wrote back.

The developers replaced the plain integer with an atomic compare-and-swap loop that decrements only if the value is still positive, and they documented the inventory class as unconditionally thread-safe. They also ran the test suite under ThreadSanitizer, which flagged a second race in a cache of seat maps. After the change, overselling stopped entirely, and latency remained within a few microseconds per update because no global lock was introduced.