I am using multiple threads… To better understand an issue, I need an answer to this rethorical question
I posted it on stack
I have two classes.
One class is just a container for a integer value with get and set synchronized methods.
public class Sync {
private int dataSync;
public synchronized int getDataSync() {
return dataSync;
}
public synchronized void setDataSync(int data) {
dataSync = data;
}
}
The other classes is similar. It is just a container for a integer value with get and set methods without synchronization.
public class NotSync {
private int dataNotSync;
public int getDataNotSync() {
return dataNotSync;
}
public void setDataNotSync(int data) {
dataNotSync = data;
}
}
Now my rhetorical question is “is 10 value guaranteed to be visible to all other threads” at the end of the run method.
public class RunSync {
public static void main(String[] args) {
RunSync rs = new RunSync();
rs.run();
}
private NotSync dataNS;
private Sync dataS;
public RunSync() {
dataS = new Sync();
dataNS = new NotSync();
}
public synchronized void run() {
dataS.setDataSync(45);
dataNS.setDataNotSync(10);
//Question A: is 10 value guaranteed to be visible to all other
//threads when method exits?
//we are inside a synchronized block aren’t we?
//so all writes must be flushed to main memory
}
}