Java Reference
In-Depth Information
inventoryLock.lock() . Any other thread that tries to acquire the invent-
oryLock lock will have to wait until the inventoryLock lock is released. At the
end of the fulfillOrder() method (in the finally block), the invent-
oryLock is released by calling the inventoryLock.unlock() method:
Lock inventoryLock = new ReentrantLock();
private boolean fulfillOrder(String itemOrdered, int
quantityOrdered, String customerName) {
try {
inventoryLock.lock();
int currentInventory
= inventoryMap.get(itemOrdered);
if (currentInventory < quantityOrdered) {
System.out.println("Couldn't fulfill order
for " + customerName +
" not enough " + itemOrdered + " ("
+ quantityOrdered + ")");
return false; // sorry, we sold out
}
inventoryMap.put(itemOrdered, currentInventory
- quantityOrdered);
CustomerOrder order = new
CustomerOrder(itemOrdered, quantityOrdered, customerName);
customerOrders.add(order);
System.out.println("Order fulfilled for "
+ customerName + " of " +
itemOrdered + " (" + quantityOrdered
+ ")");
return true;
} finally {
inventoryLock.unlock();
}
}
private void checkInventoryLevels() {
try {
inventoryLock.lock();
System.out.println("------------------------------------");
Search WWH ::




Custom Search