Creating Thread-Safe Objects with synchronized getters and setters and protect critical regions that change state - Java Thread

Java examples for Thread:Thread Safe

Description

Creating Thread-Safe Objects with synchronized getters and setters and protect critical regions that change state

Demo Code

class MyClass {//from   ww w  .  ja  v  a2 s .c  o m
  private String itemOrdered;
  private int quantityOrdered;

  public MyClass() {

  }

  public double calculateOrderTotal(double price) {
    synchronized (this) {
      return getQuantityOrdered() * price;
    }
  }

  public synchronized String getItemOrdered() {
    return itemOrdered;
  }

  public synchronized int getQuantityOrdered() {
    return quantityOrdered;
  }

  public synchronized void setItemOrdered(String itemOrdered) {
    this.itemOrdered = itemOrdered;
  }

  public synchronized void setQuantityOrdered(int quantityOrdered) {
    this.quantityOrdered = quantityOrdered;
  }
}

Related Tutorials