Consider the following code:
Thread A:
closed = true; // closed is a volatile variable
close();
Thread B:
while(true){
if(!closed){
write();
}
else {
...
}
}
If I understand correctly, closed = true;
happens-before close();
, and closed = true;
happens-before write();
, but it seems that there is no happens-before relationship between close();
and write();
.
Does the above code ensures that write();
will only get called before close()
? If it does not, what modification can be done to make it work? Or do I have to use synchronized
?