Java.Multithreading.What is “thread safety”?

🔐 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:

  1. Read count
  2. Add 1
  3. 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 of 2

✅ 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

TermMeaning
Thread-safeSafe for use by multiple threads simultaneously
Race conditionWhen outcome depends on thread timing (bug)
AtomicityOperation is indivisible (not interruptible)
Mutual exclusionOnly one thread can access critical section
This entry was posted in Без рубрики. Bookmark the permalink.