Java Reference
In-Depth Information
tions.synchronizedlist.list
iterator Javadoc). In the solution, the list can
safely be iterated while inside the
synchronized(list)
block. When synchroniz-
ing on the list, no read/updates/other iterations can occur until the
synchron-
ized(list)
block is completed.
10-5. Coordinating Different Collections
Problem
You need to modify different but related collections at the same time and you want to
ensure that no other threads can see these modifications until they have been com-
pleted.
Solution 1
By synchronizing on the principal collection, you can guarantee that collection can be
updated at the same time. In the following example, the
fulfillOrder
method
needs to check the inventory of the order to be fulfilled, and if there is enough invent-
ory to fulfill the order, it needs to add the order to the
customerOrders
list. The
fulfillOrder()
method synchronizes on the
inventoryMap
map and modifies
both the
inventoryMap
and the
customerOrders
list before finishing the syn-
chronized block.
private boolean fulfillOrder(String itemOrdered, int
quantityOrdered, String customerName) {
synchronized (inventoryMap) {
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