Straight out from Java concurrency in Practice :
@ThreadSafe
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()); }
public SafePoint(int x, int y) {
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 above is a Thread-safe class : since its setters are synchronized. I understand also why the getter doesn't individually return x / y but instead returns an array. I have 2 questions . Why ?
private SafePoint(int[] a)
public SafePoint(SafePoint p) { this(p.get()); }
instead of this(p.x,p.y);
Because calling this(p.x, p.y)
is not atomic. In other words, imagine the following thread interleaving:
read p.x
p.set(otherX, otherY);
read p.y
and call this(p.x, p.y);
The x and the y are now from two different points and possibly not consistent.
On the other hand, p.get()
reads x and y atomically (it is synchronized
) and therefore guarantees that the x and the y in the array are from the same point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With