Here's the problem I'm facing. On running the below code, I'm sometimes getting stale data when printing the content of B. I can't really understand why this is happening since updating and receiving the contents of B are protected by B's lock.
Notice that the during update to B, both the locks of A and B are held. While accessing the contents of B, only a single lock is held.
Also Notice that B.updated() is not synchronized, but I don't think this is the problem since I'm making sure that the updated counter is set to 2, before I access the content of B.
class B {
Object data
int updated = 0
// get and set protected by B's monitor
synchronized Object getData() {
return data;
}
synchronized setData(Object d) {
data = d;
updated += 1;
}
// deliberately not synchronized
int updated() { return updated; }
}
class A {
B b
A() {
new Thread t = new Thread(new UpdaterThread());
t.start();
}
// when B is updated both A and B monitors are held
synchronized String setB(Object data) {
b.setData(data);
}
class UpdateThread implements Runnable {
public void run() {
// updating B to new Value
setB("B2");
}
}
}
public static void main(String[] _) {
B b = new B();
b.setData("B1");
A a = new A();
while (b.updated() == 1) {
// wait for updated to reach 2
}
println(b.getData()); // prints "B1" sometimes, but very rarely.
}