vehicle tracker that publishes its state:
Let’s construct a version of the vehicle tracker that publishes its underlyingmutable state. we need to modify the interface a little bit to accommodate
this change, this time using mutable but thread-safe points.
public class SafePoint {
@GuardedBy("this") private int x, y;
private SafePoint(int[] a) { this(a[0], a[1]); }
public SafePoint(SafePoint p) { this(p.get()); }
this.x = x;
this.y = y;
}
public synchronized int[] get() {
return new int[] { x, y };
}
public synchronized void set(int x, int y) {
this.x = x;
this.y = y;
}
}
the code provided above gives a goods idea about how to handle the variables simultaneously,here, that's x and y, It provides a getter that retrieves both the x and y
values at once by returning a two-element array. The private constructor exists to avoid the race condition that would occur if the copy constructorwere implemented as this(p.x, p.y); this is an example of the private constructor capture idiom.