← Back to Chapters

Java Synchronization

? Java Synchronization

? Quick Overview

Synchronization in Advanced Java is used to control access to shared resources in a multithreaded environment. It prevents multiple threads from executing critical sections of code simultaneously, avoiding data inconsistency.

? Key Concepts

  • Thread Safety
  • Critical Section
  • Race Condition
  • synchronized keyword
  • Object-level and Class-level locking

? Syntax / Theory

The synchronized keyword ensures that only one thread can access a method or block at a time using an intrinsic lock.

? Code Example(s)

? View Code Example
// Synchronized method example
class Counter {
private int count = 0;

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

public int getCount() {
return count;
}
}
? View Code Example
// Synchronized block example
class Printer {
void print(String msg) {
synchronized(this) {
System.out.println(msg);
}
}
}

? Live Output / Explanation

Explanation

In the synchronized method, the lock is applied to the entire method. In the synchronized block, only the critical section is locked, improving performance by reducing lock scope.

? Interactive Simulation: The Shared Counter

Visualize how threads access a shared resource with and without locks.

Thread A
 
?
Value: 0
 
Thread B
Ready to start...

✅ Tips & Best Practices

  • Prefer synchronized blocks over synchronized methods when possible
  • Keep critical sections small
  • Avoid unnecessary synchronization to improve performance
  • Use higher-level concurrency utilities when appropriate

? Try It Yourself

  • Create two threads accessing the same synchronized method
  • Remove synchronization and observe inconsistent output
  • Experiment with class-level synchronization using static methods