The reads and writes operations are atomic for
Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization.
The java.util.concurrent.atomic package defines classes that support atomic operations on single variables in a lock-free thread-safe way
Example with an AtomicInteger, the method does not need any synchronization
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
versus the old way with synchronized method
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}