Middle
What are other ways to deal with race conditions besides using the volatile keyword?
sobes.tech AI
Answer from AI
Mutexes (synchronized blocks or functions, Lock API), atomic variables (AtomicInteger, AtomicBoolean, etc.), semaphores, monitors, channels (for data transfer between threads), and the use of data structures safe for concurrent access (e.g., ConcurrentHashMap, CopyOnWriteArrayList).
// Example with synchronized block
private final Object lock = new Object();
private int count = 0;
public void increment() {
synchronized (lock) {
count++;
}
}
// Example with AtomicInteger
private final java.util.concurrent.atomic.AtomicInteger atomicCount = new java.util.concurrent.atomic.AtomicInteger(0);
public void incrementAtomic() {
atomicCount.incrementAndGet();
}