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.
| Property | What it guarantees | Typical defect when missing |
|---|---|---|
| Atomicity | Compound updates appear indivisible | Lost updates, torn writes |
| Visibility | Writes reach other threads | Thread loops forever on a stale flag |
| Ordering | Consistent sequence of effects | Object seen before construction finishes |
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.
| Level | Meaning | Typical example |
|---|---|---|
| Immutable | State never changes after construction | String objects in Java and C# |
| Unconditionally thread-safe | Any sequence of calls is safe | Concurrent hash maps |
| Conditionally thread-safe | Safe per call, compound actions need locking | Synchronized collection wrappers |
| Thread-compatible | Safe only with external synchronization | Standard library vectors and lists |
| Thread-hostile | Unsafe even with external locking | Code that mutates global state |
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.
| Technique | How it works | Main cost or risk |
|---|---|---|
| Immutability | Objects cannot change after creation | Allocation of new copies |
| Thread confinement | Data is owned by one thread only | Requires disciplined handoff |
| Mutual exclusion | A mutex or monitor serializes access | Contention, deadlock risk |
| Atomic operations | Hardware instructions such as compare-and-swap | Hard to compose, ABA problem |
| Lock-free structures | Retry loops built on atomics | High design complexity |
| Message passing | Threads exchange copies through queues | Copying and queue latency |
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 compared with related concepts
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.
| Concept | Focus | Relation to thread safety |
|---|---|---|
| Race condition | Outcome depends on timing | The defect thread safety eliminates |
| Reentrancy | Safe re-entry during execution | Overlapping but independent property |
| Atomic operation | Single indivisible step | A building block, not a full solution |
| Deadlock freedom | Threads never block each other forever | A liveness goal beyond correctness |
| Async safety | Safe within an event loop | Concerns tasks rather than OS threads |
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.