A class or method is thread-safe if it works correctly in a multithreaded environment, even when accessed by multiple threads at the same time.
Common Thread-Safe Techniques
Technique | Purpose |
---|---|
synchronized | Locks code to prevent race conditions |
volatile | Ensures visibility across threads |
Atomic classes | Lock-free, thread-safe operations |
Immutability | Prevents shared state modification |
Thread-local storage | Isolates data per thread |
Using ExecutorService | Manages threads with safety & control |
volatile Keyword
volatile boolean flag = false;
Ensures visibility: changes made by one thread are seen by others.
Doesnβt provide atomicity (use Atomic classes for that).
Atomic Classes (from java.util.concurrent.atomic
)
Class | Usage |
---|---|
AtomicInteger | incrementAndGet(), compareAndSet() |
AtomicLong | For long values |
AtomicBoolean | For flags |
AtomicReference | For objects |
Example: AtomicInteger
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet(); // atomically adds 1
int current = count.get();
Lock-free, super fast, avoids race conditions.
Immutability = Thread Safety
final class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Immutable objects are naturally thread-safe.
Key Rule
If shared data is mutable, it must be:
- protected with synchronized or locks,
- or use atomic/immutable/thread-local alternatives.
Tip
Be ready to:
- explain how volatile and AtomicInteger differ.
- mention why immutability is a safe & simple strategy,
- recognize situations where atomic operations are better than locks.
Parent: _Multithreading