Senior
What is the 'synchronized' keyword?
sobes.tech AI
Answer from AI
The keyword synchronized in Java is used to ensure synchronized access to shared resources in a multithreaded environment. It guarantees that only one thread can execute a block of code or method marked as synchronized at a given time, preventing race conditions and ensuring data integrity.
Example of using a method with synchronized:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
Here, the increment and getCount methods are synchronized, which prevents multiple threads from accessing them simultaneously and guarantees correct updating and reading of the count variable.