-1

My question is very simple. I don't understand following concurrent programming exercise. So the question is basically what do I have to do here:

public class Point {
 private final double x, y;
 private double distance; // Hinweis: sqrt (x*x+y*y);

 public Point(final double x, final double y) {
   this.x = x;
   this.y = y;
   this.distance = -1; // Lazy: Könnte u.U. nie benötigt werden
 }

 public double getX() {    return x;   }

 public double getY() {    return y;   }

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

}

Text says: Lazy Evaluation - getDistance() is supposed to give away the distance from the point to its origin. The distance shall not be set by initializing and not be calculated over and over with each call ( because of x and y distance being constant ).

Are they asking me here to use Futures?

Best Regards.

Timo N.
  • 341
  • 3
  • 12
  • They are asking you to compute distance only once and only when needed. There's no obvious concurrent anything here. – pvg Dec 11 '15 at 15:02
  • 4
    Seriously, I downvote, SO is not a place to ask people to do your school/formation exercises... – Tancrede Chazallet Dec 11 '15 at 15:05
  • I disagree with you both, concurrency is not completely irrelevant here because 2 threads could call `getDistance` at the same time. And the fact it is for school/formation doesn't automatically disqualify the question. – cahen Dec 11 '15 at 15:09
  • If concurrency here is really a problem 'synchronize' the get function. – Andre Classen Dec 11 '15 at 15:15

1 Answers1

0

The code below would calculate the distance only once.

Are you sure the question is about concurrency? If 2 threads called getDistance() at the same time, maybe it would be calculated twice, but it's not really an overhead. But if it's imperative that the distance is calculated only once no matter what, then you need to use public synchronized double instead, more info here.

private Double distance; // changed from double to Double so it's nullable

public double getDistance() {
    if (distance == null) {
        distance = <calculate distance here>
    }

    return distance;
}
Community
  • 1
  • 1
cahen
  • 15,807
  • 13
  • 47
  • 78
  • 2
    You might want to point out more clearly that you changed the type of the `distance` field to `Double` so that you can distinguish when it has or has not been previously computed. – Rob Dec 11 '15 at 15:37