It is used to control access of critical code in multithreaded programs.
In Java, the synchronized
modifier is used to control access to a block of code or a method by multiple threads. When a method or a block of code is declared as synchronized, only one thread can access it at a time. This ensures that the critical section of code is executed by only one thread, preventing potential issues like data corruption or inconsistent state due to concurrent access.
Here are the main uses of the synchronized
modifier:
- Method Level Synchronization: When you declare a method as synchronized, only one thread can execute that method on an object at a time. Other threads attempting to call the synchronized method on the same object will be blocked until the first thread completes the execution of the method.
java
public synchronized void synchronizedMethod() {
// Code that needs to be synchronized
}
- Block Level Synchronization: You can also use the
synchronized
block to wrap a specific section of code within a method. This allows you to synchronize only a part of the method instead of the entire method.java
synchronized (lockObject) {public void someMethod() {
// Non-critical section code
// Critical section code
}
// Non-critical section code
}Here,
lockObject
is an object used for synchronization, and only one thread can execute the critical section of code enclosed within thesynchronized
block.
The main purpose of using synchronized
is to avoid race conditions and ensure the consistent and predictable behavior of shared resources in a multithreaded environment. However, it’s worth noting that excessive use of synchronization can lead to performance issues, so it should be used judiciously where necessary. Additionally, starting from Java 5, there are alternative concurrency utilities like java.util.concurrent
that provide more flexible and efficient ways to manage concurrency.