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

TechniquePurpose
synchronizedLocks code to prevent race conditions
volatileEnsures visibility across threads
Atomic classesLock-free, thread-safe operations
ImmutabilityPrevents shared state modification
Thread-local storageIsolates data per thread
Using ExecutorServiceManages 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)

ClassUsage
AtomicIntegerincrementAndGet(), compareAndSet()
AtomicLongFor long values
AtomicBooleanFor flags
AtomicReferenceFor 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