Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public interfaceclass Racer {
  public double getCurrentSpeed() {
    // ...
  }

  public double getDistance() {
    // ...
  }

  //...
}

public class Race {
  final static int MAX = 20;
  static Racer[] racers = new Racer[MAX];
 
  public Race() {
    for (int i = 0; i < MAX; i++) {
      racers[i] = new Racer(/* initialize racer */);
    }
  }

  double getAverageCurrentSpeed() {
    return averageCurrentSpeedCalculator(0, 0.0);
  }

  double averageCurrentSpeedCalculator(int i, double currentSpeed) { // Acquires locks in increasing order
    if (i > MAX - 1) {
      return currentSpeed / MAX;
    }

    synchronized(racers[i]) {
      currentSpeed += racers[i].getCurrentSpeed();
      return averageCurrentSpeedCalculator(++i, currentSpeed);
    }	 
  }


  double getAverageDistance() {
    return averageDistanceCalculator(MAX - 1, 0.0);
  }

  double averageDistanceCalculator(int i, double distance) { // Acquires locks in decreasing order
    if (i <= -1) {		 
      return distance / MAX;
    } 

    synchronized(racers[i]) {
      distance += racers[i].getDistance();
      return averageDistanceCalculator(--i, distance);
    }
  }
}

...