...
Code Block | ||
---|---|---|
| ||
final class Adder { private final AtomicIntegerint a = new AtomicInteger(); private finalint AtomicInteger b = new AtomicInteger(); public synchronized int getSum() { return a.get() + b.get(); // or, return a.getAndAdd(b.get()); } public synchronized void setValues(int a, int b) { this.a.set(a) = a; this.b.set(b) = 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.
...