Unit 4 Synchronization
Unit 4 Synchronization
SYNCHRONIZATION
5. SYNCHRONIZATION:
Synchronization is a process that controls the access of multiple threads to shared resources. When
multiple threads try to access the same resource (like a variable, method, or object) at the same time,
it can lead to inconsistent or incorrect data. Synchronization ensures that only one thread can
access the resource at a time, preventing data corruption and ensuring thread safety.
• Java provides the synchronized keyword to control access to a block of code or a method. When a
• The thread acquires a lock (monitor) on the object before executing the code.
• This ensures mutual exclusion — only one thread can run the synchronized code at a time.
Types of Synchronization in Java
Synchronized Method
• The entire method is locked so only one thread can run it at a time.
• Declared by adding synchronized keyword to the method.
Example:
public synchronized void display() {
// code here
}
Synchronized Block
• Only a part (block) of the method is locked, not the whole method.
• Allows better control and improves performance by locking only necessary code.
Example:
public void display() {
synchronized(this) {
// critical code here
}
}
Thank You