Middle
How do you ensure synchronization in a multithreaded environment?
sobes.tech AI
Answer from AI
In Java, synchronization in a multithreaded environment is achieved using the synchronized keyword, classes from the java.util.concurrent package, and atomic operations.
- The
synchronizedblock locks access to a critical section of code, ensuring that only one thread executes it at a time.
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
-
Classes from
java.util.concurrent(e.g.,ReentrantLock,AtomicInteger) provide more flexible and efficient synchronization mechanisms. -
To avoid race conditions, it is important to use these mechanisms correctly to ensure thread safety.
For example, using AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
Thus, synchronization prevents concurrent modification of shared data by multiple threads, ensuring the correctness of the program.