Junior — Middle
Explain the working principle of the synchronized keyword in Java and its impact on thread safety of data.
sobes.tech AI
Answer from AI
The synchronized keyword in Java is used to ensure thread safety when accessing shared resources. It locks the monitor object so that only one thread can execute the code inside the block or method marked synchronized.
This prevents multiple threads from modifying data simultaneously, which could lead to race conditions and incorrect results.
Example:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
In this example, the increment and getCount methods are synchronized, so changes to and reading of count happen atomically and safely in a multithreaded environment.