...
In this noncompliant code example, the field itemsInInventory
can be accessed by multiple threads. However, when a thread is updating the value of itemsInInventory
, it is possible for other threads to read the original value (that is, the value before the update). This is because the post decrement operator is non-atomic.
...
Constructors and methods can make use of an alternative representation called block synchronization which synchronizes a block of code rather than a method, as highlighted below.
Code Block | ||
---|---|---|
| ||
private volatile int itemsInInventory = 100; public int removeItem() { if(itemsInInventory > 0) { synchronized(this) { return itemsInInventory--; // Returns new count of items in inventory } } else { return 0; } } |
Block synchronization is more preferable than method synchronization because it reduces the period for which the lock is held and also protects against denial of service attacks. The variable itemsInInventory
still needs to be declared volatile
because the check to determine whether it is greater than 0 relies on the latest value of the variable. An alternative to avoid the need to declare the variable volatile
is to use block synchronization across the whole if-else
block. However, this alternative is more costly.
Risk Assessment
If access to operations on shared, mutable variables is are not synchronizedatomic, unexpected results may be produced. For example, there can be inadvertent information disclosure as one user may be able to receive information about other users.
...