Skip to content
Thread Safety — Explained with Examples

Thread Safety — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

Thread safety ensures shared data behaves correctly when accessed by multiple threads, preventing race conditions and data corruption.

Thread safety is achieved through several strategies: immutability (objects cannot change after creation — inherently thread-safe), synchronization (mutexes, semaphores), thread-local storage (each thread has its own copy), atomic operations (CAS-based primitives), and reentrant code (functions that work correctly when called concurrently). A class or function is thread-safe if it maintains invariants under any interleaving of thread operations.

Think of thread safety like a roundabout versus a traffic light intersection. A roundabout (immutability/thread-local) has no shared stopping point — cars flow naturally without conflict. A traffic light (synchronization) coordinates access to a shared space, ensuring only one direction moves at a time.

Achieving thread safety requires understanding both the data structure and the access patterns. Immutable objects (like str in Python, String in Java) are always thread-safe. Mutable objects require explicit design.

import threading

# NOT thread-safe
class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1  # Read-modify-write, not atomic

# Thread-safe using mutex
class SafeCounter:
    def __init__(self):
        self.count = 0
        self.lock = threading.Lock()

    def increment(self):
        with self.lock:
            self.count += 1

# Thread-safe using atomic (Python's GIL makes this safe for ints)
# But relying on GIL for thread safety is poor practice

# Thread-safe using immutable style
from dataclasses import dataclass
@dataclass(frozen=True)
class ImmutableCounter:
    count: int

    def increment(self):
        return ImmutableCounter(self.count + 1)

counter = SafeCounter()
threads = [threading.Thread(target=counter.increment) for _ in range(100)]
for t in threads: t.start()
for t in threads: t.join()
print(counter.count)  # 100

Document thread safety guarantees clearly: whether a class is thread-safe, conditionally safe, or not thread-safe. Users should not have to guess.

Mutex, Race Condition, Critical Section, Lock-Free Programming, Deadlock

Race Condition Mitigation

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro