Thread-safe synchronized

In Java, "thread-safe synchronized" refers to the practice of designing and implementing code in a way that allows multiple threads to access shared resources concurrently without causing data corruption or inconsistent states. The synchronized keyword is a fundamental mechanism in Java for achieving thread safety.

Thread Safety:

A class or method is considered thread-safe if it behaves correctly when accessed by multiple threads simultaneously, regardless of the order in which those threads execute. This means that the internal state of the object remains consistent and correct, even with concurrent modifications.

Synchronization with synchronized:

The synchronized keyword provides a built-in mechanism for mutual exclusion and visibility in Java:
  • Synchronized Methods: When a method is declared synchronized, the entire method body becomes a critical section. Only one thread can execute a synchronized method on a given object at any time. Other threads attempting to call a synchronized method on the same object will block until the current thread releases the lock.
     public class Counter {
private int count = 0;

public synchronized void increment() {
count++;
}

public synchronized int getCount() {
return count;
}
}

  • Synchronized Blocks: The synchronized keyword can also be applied to a specific block of code, allowing for finer-grained control over synchronization. This requires specifying an object that serves as the lock (monitor). Only one thread can execute the synchronized block while holding the lock on that specific object.

    public class DataProcessor {
private Object lock = new Object();
private List<String> data = new ArrayList<>();

public void addData(String item) {
synchronized (lock) { // Synchronized block using 'lock' object
data.add(item);
}
}
}​​


How synchronized Achieves Thread Safety:

  • Mutual Exclusion:
    synchronized ensures that only one thread can execute a synchronized method or block on a given object at a time, preventing race conditions where multiple threads try to modify shared data simultaneously.
  • Visibility:
    synchronized guarantees that changes made by one thread to shared variables within a synchronized block or method are visible to other threads when they subsequently enter a synchronized section on the same object. This prevents stale data issues.


Other Thread Safety Mechanisms:

While synchronized is a primary tool, other mechanisms also contribute to thread safety in Java, including:
  • java.util.concurrent package:
    Provides advanced synchronization utilities like ReentrantLock, ReadWriteLock, Semaphore, and thread-safe collections like ConcurrentHashMap and CopyOnWriteArrayList.
  • Atomic classes:
    Classes like AtomicInteger, AtomicLong, and AtomicReference offer atomic operations on single variables without explicit locking, often providing better performance than general-purpose synchronization.
  • Immutable objects:
    Objects whose state cannot be changed after creation are inherently thread-safe, as there's no risk of concurrent modification. (e.g., String in Java).

← Back to Learning Journey