Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet189/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   185   186   187   188   189   190   191   192   ...   245
Bog'liq
Java 17 Recipes

 Solution 2
Using a reentrant lock, you can prevent multiple threads from accessing the same 
critical area of the code. In this solution, the inventoryLock is acquired by calling 
inventoryLock.lock(). Any other thread that tries to acquire the inventoryLock lock 
must wait until the inventoryLock lock is released. At the end of the fulfillOrder() 
method (in the finally block), the inventoryLock 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();
}
}
Chapter 10 ConCurrenCy


370
private void checkInventoryLevels() {
try {
inventoryLock.lock();
System.out.println("------------------------------------");
inventoryMap.entrySet().stream().forEach((inventoryEntry) -> {
System.out.println("Inventory Level :" + inventoryEntry 
.getKey() + " " + inventoryEntry.getValue());
});
System.out.println("------------------------------------");
} finally {
inventoryLock.unlock();
}
}
private void displayOrders() {
try {
inventoryLock.lock();
customerOrders.stream().forEach((order) -> {
System.out.println(order.getQuantityOrdered() + " " +
order.getItemOrdered() + " for " + order.getCustomerName());
});
} finally {
inventoryLock.unlock();
}
}

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   185   186   187   188   189   190   191   192   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling