1. Synchronized Methods

Technical Explanation

  • Mechanism: Locks entire method for a thread
  • Scope: Entire method becomes a critical section
  • Object-level Locking: Uses object's intrinsic lock
  • Performance Impact: Higher overhead compared to blocks

public class SynchronizedMethodExample {
    // Synchronized method prevents concurrent access
    public synchronized void criticalMethod() {
        // Only one thread can execute this method at a time
        // Shared resource modifications happen here
    }
    
    // Alternative explicit synchronization
    public void explicitSyncMethod() {
        synchronized(this) {
            // Synchronized block with same effect
        }
    }
}
                                        

2. Synchronized Blocks

Technical Explanation

  • Mechanism: Lock specific code sections
  • Granularity: More fine-grained control
  • Performance: Less overhead than full method sync
  • Flexibility: Can use different lock objects

public class SynchronizedBlockExample {
    private final Object lock = new Object();
    private int sharedResource;
    
    public void modifyResource() {
        // Synchronized block with custom lock object
        synchronized(lock) {
            // Critical section
            sharedResource++;
        }
    }
}
                                        

3. Atomic Operations

Technical Explanation

  • Mechanism: Thread-safe operations without explicit locking
  • Implementation: Hardware-level atomic instructions
  • Performance: Very efficient synchronization
  • Use Cases: Counters, simple numeric operations

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicOperationExample {
    private AtomicInteger counter = new AtomicInteger(0);
    
    public void incrementCounter() {
        // Atomic increment operation
        counter.incrementAndGet();
    }
    
    public int getCounterValue() {
        return counter.get();
    }
}