mercredi 25 février 2015

Do I need to make both variables volatile in reader/writer scenario?



We have 2 threads. One is a reader. The other is a writer thread who share these 2 variables:



Object data
boolean ready


Do I need to make both volatile? Is it sufficient to make 'ready' volatile?



write() {
data = <some data>
ready = true;
}

read() {
if (ready) {
consume(data);
ready = false;
}
}


Do I need to make both variables volatile?


Based on my limited understnding of the java memory model, I think I only have to make 'ready' volatile as all the code before reading/writing 'ready' happens-before the code after the reading/writing of 'ready' variable?


Update: For the purposes of this question, assume that atomicity is not an issue. The production and consumption of data is atomic.




Aucun commentaire:

Enregistrer un commentaire