Here is the original code
//@author Brian Goetz and Tim Peierls
@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.set(x, y);
}
public synchronized int[] get() {
return new int[]{x, y};
}
public synchronized void set(int x, int y) {
this.x = x;
this.y = y;
}
}
Here it is fine that the private int x,y are not final because the set method in the constructor makes for a happens before relationship when calling get because they use the same lock.
Now here is the modified version and a main method that I expected to throw an AssertionError after running it for a little bit because I removed the synchronized keyword in the set method. I made it private for the constructor to be the only one calling it in case someone was going to point out that it's not thread-safe because of it, which isn't the focus of my question.
Anyhow, I've waited quite a bit now, and no AssertionErrors were thrown. Now I am weary that this modified class is somehow thread-safe, even though from what I've learned, this is not because the x and y are not final. Can someone tell me why AssertionError is still never thrown?
public class SafePointProblem {
static SafePoint sp = new SafePoint(1, 1);
public static void main(String[] args) {
new Thread(() -> {
while (true) {
final int finalI = new Random().nextInt(50);
new Thread(() -> {
sp = new SafePoint(finalI, finalI);
}).start();
}
}).start();
while (true) {
new Thread(() -> {
sp.assertSanity();
int[] xy = sp.get();
if (xy[0] != xy[1]) {
throw new AssertionError("This statement is false 1.");
}
}).start();
}
}
}
class SafePoint {
private int x, y;
public SafePoint(int x, int y) {
this.set(x, y);
}
public synchronized int[] get() {
return new int[]{x, y};
}
// I removed the synchronized from here
private void set(int x, int y) {
this.x = x;
this.y = y;
}
public void assertSanity() {
if (x != y) {
throw new AssertionError("This statement is false2.");
}
}
}