Junior — Middle
In what cases have you used synchronized blocks in your code to manage threads?
sobes.tech AI
Answer from AI
The synchronized blocks in Java are used to control access to shared resources in multithreaded applications to prevent race conditions and ensure data correctness. For example, when multiple threads simultaneously modify a shared counter or collection, I wrap the critical section in a synchronized block so that only one thread can execute that code at a specific time.
Example:
public class Counter {
private int count = 0;
public void increment() {
synchronized(this) {
count++;
}
}
public int getCount() {
return count;
}
}
Here, synchronized(this) guarantees that the counter increment is atomic, preventing possible errors during concurrent access from different threads.