Java Reference
In-Depth Information
Solution 1
Use synchronized getters and setters and protect critical regions that change state. In
the following example, an object is created with getters and setters that are synchron-
ized for each internal variable. The critical regions are protected by using the syn-
chronized(this) lock:
class CustomerOrder {
private String itemOrdered;
private int quantityOrdered;
private String customerName;
public CustomerOrder() {
}
public double calculateOrderTotal (double price) {
synchronized (this) {
return getQuantityOrdered()*price;
}
}
public synchronized String getItemOrdered() {
return itemOrdered;
}
public synchronized int getQuantityOrdered() {
return quantityOrdered;
}
public synchronized String getCustomerName() {
return customerName;
}
public synchronized void setItemOrdered(String
itemOrdered) {
this.itemOrdered = itemOrdered;
}
Search WWH ::




Custom Search