The synchronized keyword in Java is used to create synchronized blocks or synchronized methods. These constructs are used to ensure that only one thread can execute a block of code or method at a time, preventing race conditions and data inconsistencies when multiple threads access shared resources.
Here are the two ways to use the synchronized keyword in Java:
Synchronized blocks: A synchronized block is a block of code that is synchronized on a specific object. Only one thread can execute the synchronized block at a time, preventing other threads from modifying the shared resource simultaneously. Here’s an example of a synchronized block:
public class SharedResource {
private int counter;
public void increment() {
synchronized(this) {
counter++;
}
}
}
In this example, we define a class called SharedResource that contains a counter variable. The increment() method is synchronized on the instance of the SharedResource class, using the synchronized(this) block. This ensures that only one thread can modify the counter variable at a time.
Synchronized methods: A synchronized method is a method that is synchronized on the object instance. When a thread calls a synchronized method, it acquires the lock on the object instance, preventing other threads from accessing the same object until the method completes. Here’s an example of a synchronized method:
public class SharedResource {
private int counter;
public synchronized void increment() {
counter++;
}
}
In this example, we define a class called SharedResource that contains a counter variable. The increment() method is declared as synchronized, which means that only one thread can execute the method at a time. When a thread calls the increment() method, it acquires the lock on the instance of the SharedResource class, preventing other threads from calling the method until it completes.
Overall, the synchronized keyword is used to create synchronized blocks or synchronized methods, which ensure that only one thread can execute a block of code or method at a time, preventing race conditions and data inconsistencies when multiple threads access shared resources. Synchronization is an important mechanism for creating thread-safe applications in Java.