Synchronization

Thinking

In a multi-threaded environment, multiple threads accessing and modifying shared resources can lead to inconsistent or incorrect data. This is known as a race condition.

Synchronization ensures controlled access to these resources so that only one thread can access the critical section at a time, preserving data consistency and thread safety.

Description

Synchronization in Java is the mechanism that allows controlling access to shared resources by multiple threads. It prevents thread interference and memory consistency errors by ensuring that only one thread can access the critical section of code at a time.

Key Concepts:

  • Critical Section: A part of code that accesses shared resources and must not be concurrently executed by more than one thread.
  • synchronized Keyword: Used to lock an object or method so only one thread can execute it at a time.
  • Object Monitor: Each object in Java has an associated monitor that can be locked or unlocked using synchronization.
  • Deadlock: A situation where two or more threads are blocked forever, waiting for each other to release locks.
<

Video Resources

Examples (code)

Synchronized Method Example


class SharedCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
        System.out.println(Thread.currentThread().getName() + " Count: " + count);
    }
}

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

        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task, "Thread-1");
        Thread t2 = new Thread(task, "Thread-2");

        t1.start();
        t2.start();
    }
}
  

Real-World Applications

Online Transactions

Ensures account balances are correctly updated even when multiple transactions occur simultaneously.

Database Writes

Prevents data corruption when multiple threads attempt to write to a database table at the same time.

Multiplayer Games

Controls access to shared game states like scores, positions, and inventory to avoid inconsistencies.

Interview Questions

Q1: What is synchronization in Java?

Show Answer

Synchronization is a mechanism that ensures only one thread accesses a critical section of code at a time, preventing race conditions and data inconsistencies.

Q2: What are the types of synchronization in Java?

Show Answer

Java supports two types: method-level synchronization and block-level synchronization, both using the synchronized keyword.

Q3: What is the difference between synchronized method and synchronized block?

Show Answer

A synchronized method locks the entire method, while a synchronized block allows finer control by locking only specific parts of the code using a specific object.

Q4: What is a deadlock and how can it be avoided?

Show Answer

A deadlock occurs when two or more threads wait indefinitely for each other to release locks. It can be avoided by acquiring locks in a consistent order and using try-locks or timeouts.