Java Synchronization

Synchronization in Java is the technique of controlling access to shared resources by multiple threads to avoid data inconsistency. It ensures that only one thread can access the critical section of code at a time.

Why Synchronization?

In a multithreaded environment, multiple threads may try to access shared data simultaneously, leading to race conditions and data inconsistencies. Synchronization helps prevent such issues.

Synchronized Methods:

You can use the synchronized keyword to make methods thread-safe by ensuring that only one thread can execute the synchronized method at a time.


class Counter {
  private int count = 0;

  // Synchronized method
  public synchronized void increment() {
    count++;
  }

  // Other non-synchronized methods
  public int getCount() {
    return count;
  }
}

public class SynchronizedMethodExample {
  public static void main(String[] args) {
    Counter counter = new Counter();

    // Multiple threads incrementing the count
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        for (int j = 0; j < 100000; j++) {
          counter.increment();
        }
      }).start();
    }

    // Wait for all threads to finish
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("Final Count: " + counter.getCount());
  }
}

Object-level Synchronization:

You can use the synchronized block to synchronize a specific block of code, using an object as a lock.


class Counter {
  private int count = 0;
  private final Object lock = new Object();

  // Synchronized block
  public void increment() {
    synchronized (lock) {
      count++;
    }
  }

  // Other non-synchronized methods
  public int getCount() {
    return count;
  }
}

public class SynchronizedBlockExample {
  public static void main(String[] args) {
    Counter counter = new Counter();

    // Multiple threads incrementing the count
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        for (int j = 0; j < 100000; j++) {
          counter.increment();
        }
      }).start();
    }

    // Wait for all threads to finish
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("Final Count: " + counter.getCount());
  }
}

Deadlock:

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. Avoiding deadlock is essential when dealing with synchronization.

Note:

While synchronization solves many multithreading issues, it may introduce performance overhead. It's crucial to use synchronization judiciously and consider other concurrency mechanisms when appropriate.