public class MutablePoint { private volatile int x, y; public MutablePoint(int x, int y) { this.x = x; this.y = y; } public synchronized void setX(int v) { x = v; } public synchronized void setY(int v) { y = v; } public int getX() { return x; } // no sync OK since x is volatile public int getY() { return y; } // no sync OK since y is volatile // This method is complicated because we have to make sure that // the X and Y values we compare are consistent---that a mutation // does not occur after retrieving one integer but before // retrieving the other public boolean equals(Object o) { if (o instanceof MutablePoint) { MutablePoint p = (MutablePoint)o; int px, py; synchronized (p) { px = p.getX(); py = p.getY(); } synchronized (this) { return (px == getX() && py == getY()); } } return false; } }