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.
The synchronized keyword ensures that only one thread can access a method or block at a time using an intrinsic lock.
// Synchronized method example
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
// Synchronized block example
class Printer {
void print(String msg) {
synchronized(this) {
System.out.println(msg);
}
}
}
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.
Visualize how threads access a shared resource with and without locks.