Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
class Stocks implements FundConstants {
  static int[] balances = new int[noOfStocks];
  static Object[] locks = new Object[noOfStocks];
  static
  {
    for (int n=0; n<noOfStocks; n++) {
      balances[n] = 10000;
      locks[n] = new Object();
    }
  }

  static void transfer(Transfer t) {
    int lo, hi;
    if (t.fundFrom > t.fundTo) {// acquires the monitors in decreasing numeric order
      lo = t.fundFrom;
      hi = t.fundTo;
     } else {
      lo = t.fundTo;
      hi = t.fundFrom;
     }
     
     synchronized (locks[lo]) {
       synchronized (locks[hi]) {
         balances[t.fundFrom] -= t.amount;
         balances[t.fundTo] += t.amount;
       }
      }
    }

  static int sumHelper (int next) {
    synchronized (locks[next]) {
      if (next == (noOfStocks-1)) {
        return balances[next];
      } else {
       return balances[next] + sumHelper(next+1);
     }
   }
 }

  static void checkSystem() {
    int actual = 0;
    actual = sumHelper(0);
    System.out.println("Actual balance is" + actual);
  }
}

...

Code Block
bgColor#ccccff
class Stocks implements FundConstants {
  static int[] balances = new int[noOfStocks];
  static Object[] locks = new Object[noOfStocks];
  
  static
  {
     for (int n=0; n<noOfStocks; n++) {
       balances[n] = 10000;
       locks[n] = new Object();
     }
  }

  static void transfer(Transfer t) {
    int lo, hi;
    if (t.fundFrom < t.fundTo) {
      lo = t.fundFrom;
      hi = t.fundTo;
    } else {
        lo = t.fundTo;
        hi = t.fundFrom;
    }
    synchronized (locks[lo]) {
      synchronized (locks[hi]) {
        balances[t.fundFrom] -= t.amount;
        balances[t.fundTo] += t.amount;
      }
    }
  }

  static int sumHelper (int next) {
    synchronized (locks[next]) {
      if (next == (noOfStocks-1)) {
        return balances[next];
      } else {
        return balances[next] +
        sumHelper(next+1);
      }
    }
  }

  static void checkSystem() {
    int actual = 0;
    actual = sumHelper(0);
    System.out.println("Actual balance is " + actual);
  }
}

...