How can you ensure safe updating of a variable that is accessed by multiple threads simultaneously?
sobes.tech AI
Answer from AI
There are several approaches to safely update a variable that is accessed concurrently by multiple threads:
-
Synchronization (synchronized) — locking a critical section of code so that only one thread can modify the variable at a time.
-
Classes from the java.util.concurrent.atomic package — for example,
AtomicInteger,AtomicReference, etc., which provide atomic operations without explicit synchronization. -
Using volatile — guarantees visibility of changes to the variable between threads, but does not ensure atomicity of complex operations.
-
Lock (java.util.concurrent.locks.Lock) — a more flexible locking mechanism.
Example with AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet(); // atomic increment
}
public int getCount() {
return count.get();
}
}
This approach allows safe updating of the value without the risk of race conditions.