Search code examples
javalazy-evaluationconcurrent-programming

Lazy-programming in Java


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.


Solution

  • 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;
    }