...
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.
Compliant Solution (4) (ReentrantLock
)
This compliant solution uses a java.util.concurrent.locks.ReentrantLock
to atomically perform the operation.
Code Block | ||
---|---|---|
| ||
public class Sync {
private int itemsInInventory = 100;
private final Lock lock = new ReentrantLock();
public int removeItem() {
Boolean myLock = false;
try {
myLock = lock.tryLock();
if(itemsInInventory > 0) {
return itemsInInventory--;
}
} finally {
if (myLock) {
lock.unlock();
}
}
return 0;
}
}
|
Code that uses this lock behaves similar to synchronized code that uses the traditional monitor lock. In addition, it provides several other capabilities, for instance, the tryLock()
method does not block waiting if another thread is already holding the lock.
Noncompliant Code Example (AtomicReference)
...