having a look at the netbeans affable bean tutorial. Why do we need the use of synchronized methods here?
public synchronized int getNumberOfItems() {
numberOfItems = 0;
for (ShoppingCartItem scItem : items) {
numberOfItems += scItem.getQuantity();
}
return numberOfItems;
}
public synchronized double getSubtotal() {
double amount = 0;
for (ShoppingCartItem scItem : items) {
Product product = (Product) scItem.getProduct();
amount += (scItem.getQuantity() * product.getPrice().doubleValue());
}
return amount;
}
Looks like every method related to the ShoppingCartItems management is synchronized. Certainly to prevent a concurrent access in the items List (
List<ShoppingCartItem> items;).Without the synchronized, you could have 1+ Thread accessing a ‘read’ method such as
getSubtotal ()while theitemsList is being updated through publicsynchronized void addItem(Product product)by another Thread.The source can be found here