...
Code Block | ||
---|---|---|
| ||
final class Adder { private final AtomicInteger a = new AtomicInteger(); private final AtomicInteger b = new AtomicInteger(); public int getSum() throws ArithmeticException { return a.get() + b.get(); // or, return a.getAndAdd(b.get()); } public void setValues(int a, int b) { this.a = a.set(a); this.b = b.set(b); } } |
This does not eliminate the data race because compound operation a + b
is still non-atomic.
...
Code Block | ||
---|---|---|
| ||
final class Adder { private final intAtomicInteger a = new AtomicInteger(); private final intAtomicInteger b = new AtomicInteger(); public synchronized int getSum() throws ArithmeticException { return a.get() + b.get(); // or, return a.getAndAdd(b.get()); } public synchronized void setValues(int a, int b) { this.a = a.set(a); this.b = b.set(b); } } |
Any operations within the synchronized methods are now atomic with respect to other synchronized methods that lock on that object's monitor (intrinsic lock). It is now possible, for example, to add overflow checking within the synchronized getSum()
method without introducing the possibility of a data race.
...