Java Reference
In-Depth Information
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();
}
}
How It Works
If you have different structures that are required to be modified at the same time, you
need to make sure that these structures are updated atomically. An atomic operation
refers to a set of instructions that can be executed as a whole or none at all. An atomic
operation is visible to the rest of the program only when it is complete.
In solution 1 (atomically modifying both the inventoryMap map and the cus-
tomerOrders list), you pick a “principal” collection on which you will lock (the
inventoryMap ). By locking on the principal collection, you guarantee that if anoth-
er thread tries to lock on the same principal collection, it will have to wait until the cur-
rent executing thread releases the lock on the collection.
Search WWH ::




Custom Search