...
Code Block | ||
---|---|---|
| ||
final class Adder {
private final AtomicInteger a = new AtomicInteger();
private final AtomicInteger b = new AtomicInteger();
public int getSum() {
return a.get() + b.get(); // or, return a.getAndAdd(b.get());
}
public void setValues(int a, int b) {
this.a.set(a);
this.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.
The getSum()
method does not require any synchronization if a.getAndAdd(b.get())
is used to add a
and b
because AtomicInteger.getAndAdd()
performs the addition atomically.
Risk Assessment
If operations on shared variables are not atomic, unexpected results can be produced. For example, information can be disclosed inadvertently because one user can receive information about other users.
...