Thread Safety
TL;DR
Thread-safe code produces correct results regardless of how multiple threads interleave — achieved through immutability, atomic operations, or synchronisation primitives.
Explanation
Code is thread-safe if it behaves correctly when multiple threads execute it simultaneously. Strategies: (1) Immutability — objects that cannot be modified are inherently thread-safe. (2) Thread-local storage — each thread has its own copy of mutable state. (3) Atomic operations — hardware-level indivisible read-modify-write. (4) Synchronisation — mutexes/locks. (5) Stateless design — functions with no shared state are thread-safe. In PHP: the language runtime is not thread-safe by default (ZTS — Zend Thread Safety — is a compile option). PHP-FPM uses separate processes (not threads) so most PHP code is safe. Extensions may not be ZTS-compiled. Swoole and ReactPHP introduce real concurrency within one process.
Common Misconception
✗ PHP is immune to concurrency issues because it's single-threaded — PHP-FPM runs many processes concurrently, all hitting shared resources (DB, files, cache). Concurrency bugs are real.
Why It Matters
Stateless, immutable design is the most reliable path to thread safety — and also makes code easier to test and reason about.
Common Mistakes
- Mutable static/global state in classes — shared across requests in Swoole/FrankenPHP.
- Assuming global state is safe in PHP-FPM — each process has its own, but shared resources (DB, Redis) still need protection.
- Not marking PHP extensions as ZTS-safe when using threaded PHP.
Code Examples
✗ Vulnerable
// Mutable static — breaks in Swoole/FrankenPHP:
class RequestContext {
private static ?User $currentUser = null;
public static function setUser(User $u): void { self::$currentUser = $u; }
}
✓ Fixed
// Immutable request context — safe in all runtimes:
class RequestContext {
public function __construct(
public readonly User $user,
public readonly string $requestId,
) {}
}
// Pass as dependency, not global static
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Edited
5 Apr 2026
Views
25
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Perplexity 8
Amazonbot 6
Unknown AI 3
Google 2
Ahrefs 2
ChatGPT 2
Also referenced
How they use it
crawler 20
crawler_json 2
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟠 High
⚙ Fix effort: Medium
⚡ Quick Fix
Prefer immutable objects and stateless functions. Avoid static mutable state — breaks under Swoole/FrankenPHP. Protect shared resources (files, DB, cache) with locks.
📦 Applies To
PHP 7.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
static \$|static::
Auto-detectable:
✗ No
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: High
Context: Class
Tests: Update
CWE-362
CWE-820