...
Wiki Markup |
---|
Synchronization is more expensive than using the optimized {{java.util.concurrent}} utilities and should only be used when the utilities do not contain the required method to carry out the atomic operation. When using explicit synchronization, the programmer must also ensure that two or more threads are not mutually accessible from a different set of two or more threads such that each thread holds a lock while trying to obtain another lock that is held by the other thread \[[Lea 00|AA. Java References#Lea 00]\]. Failure to follow this advice results in deadlocks ([CON11-J. Avoid deadlock by requesting locks in the proper order]). |
Compliant Solution (2)
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 preferable because it reduces the period for which the lock is held. 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 is more costly.
Risk Assessment
If access to shared, mutable variables is not synchronized, 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.
...