🔐 What Is Thread Safety?
Thread safety means:
A piece of code or a data structure behaves correctly when accessed by multiple threads at the same time, without causing:
- data corruption,
- race conditions,
- unexpected behavior.
In simple terms: It works as expected no matter how many threads use it simultaneously.
🧩 Why Thread Safety Is Hard
In multi-threaded environments:
- Threads can interleave in unpredictable ways
- Read/write operations can happen simultaneously
- Without precautions, this can cause inconsistent state
💥 Example of a Non-Thread-Safe Operation
class Counter {
int count = 0;
void increment() {
count++; // Not thread-safe!
}
}
The count++
looks innocent but is actually:
- Read
count
- Add 1
- Write back
If two threads do this at the same time:
- Both may read
count = 0
- Both write
count = 1
- ❌ Final result:
count == 1
instead of2
✅ How to Make It Thread-Safe
1. Use synchronized
synchronized void increment() {
count++;
}
Ensures mutual exclusion — only one thread can run this at a time.
2. Use AtomicInteger
AtomicInteger count = new AtomicInteger();
void increment() {
count.incrementAndGet();
}
Performs atomic operations internally, lock-free.
3. Use Thread-Safe Collections
Use classes from java.util.concurrent
, like:
ConcurrentHashMap
CopyOnWriteArrayList
BlockingQueue
🧠 General Rule
A class or method is thread-safe if:
- It behaves correctly under concurrent access
- You don’t need external synchronization when using it
📋 Summary
Term | Meaning |
---|---|
Thread-safe | Safe for use by multiple threads simultaneously |
Race condition | When outcome depends on thread timing (bug) |
Atomicity | Operation is indivisible (not interruptible) |
Mutual exclusion | Only one thread can access critical section |