Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Synchronization? Explain synchronized keyword and mutex concept. Synchronization क्या है? Synchronized keyword और mutex concept explain करें।

Answer

Synchronization prevents multiple threads from accessing shared resources simultaneously, causing data corruption. It ensures only one thread accesses critical section at a time using locks/monitors.

// Problem: Without Synchronization
public class Counter {
    private int count = 0;
    
    public void increment() {
        count++;  // NOT atomic - race condition!
    }
}

// Two threads increment() simultaneously:
// Expected: count = 2
// Actual: count = 1 (race condition)

// Solution 1: Synchronized method
public class SynchronizedCounter {
    private int count = 0;
    
    public synchronized void increment() {
        count++;  // Only one thread at a time
    }
    
    public synchronized int getCount() {
        return count;
    }
}

// Solution 2: Synchronized block
public class SyncBlockCounter {
    private int count = 0;
    private final Object lock = new Object();
    
    public void increment() {
        synchronized(lock) {  // Lock on specific object
            count++;
        }
    }
}

// How Synchronization Works:
// 1. Each object has internal lock (monitor)
// 2. synchronized keyword acquires lock
// 3. Other threads wait for lock release
// 4. Lock automatically released when block ends

// Synchronized vs Unsynchronized Performance:
public class SyncPerformanceDemo {
    public static void main(String[] args) {
        Counter unsync = new Counter();
        SynchronizedCounter sync = new SynchronizedCounter();
        
        // Unsynchronized: ~10ms (race conditions!)
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000; i++) {
            unsync.increment();
        }
        System.out.println('Unsync time: ' + 
            (System.currentTimeMillis() - start) + 'ms');
        
        // Synchronized: ~100ms (safe but slower)
        start = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000; i++) {
            sync.increment();
        }
        System.out.println('Sync time: ' + 
            (System.currentTimeMillis() - start) + 'ms');
    }
}
Synchronization:

Problem: Race conditions
- Multiple threads shared resource access करते हैं
- Data corruption होता है

Solution: Synchronization

Method 1: Synchronized method
public synchronized void method() {
    // Critical section
}

Method 2: Synchronized block
synchronized(lock) {
    // Critical section
}

Mutex: Mutual exclusion lock
- एक बार में एक thread ही lock ले सकता है
- Other threads queue में wait करते हैं

Cost: Performance penalty (10x slower)

Was this answer clear?