1

I have a few questions regarding volatile variables which are not long, double

1.is there a possibility of race condition when we write and read- meaning for example- while we read a volatile variable, someone can write a new value and the reading thread will not get the updated value?

2.can 2 writing threads write value and at the end, one of them will overlap the result of the other, also can a volatile be read with many threads at the same time meaning the reading threads overlap and all read the same result at the same time?

3.If we start 5 read and 5 write threads on 1 volatile variable, the result for the readers is unpredictable?

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • Also, read this: https://www.ibm.com/developerworks/java/library/j-jtp06197/ – daniu Mar 22 '18 at 11:58
  • It sounds as if you're writing polling code. If you need to act on each change in a volatile variable, you'll need something better than that. – Paul Janssens Mar 22 '18 at 12:03

1 Answers1

2
  1. Yes. You don't know which one happens first, so your reading thread sees one of two values.

  2. If you mean overwrite, of course. If you have 2 writes then the last one wins. If you mean overlapping as in the resulting value becoming a combination of the two writes, then no. Not even with long and double.

  3. Definitely. Unless you have for example volatile int foo = 0; and all the writers write 0. Then you're guaranteed that all the readers will see 0, otherwise it depends on scheduling and other such things.

All your questions look like you expect volatile to have something to do with order, but that's not true. It just guarantees visibility. If you want order, you'll have to enforce that yourself.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Thanks for the nice explanation and one more last question regarding question 1. so we are reading value and meantime someone sets a new value(let's say 10 ) we will read the last seen value by the last writer who ofcourse is not that one that just set 10? – user9534448 Mar 22 '18 at 12:25
  • There's no "same time". Either the reader reads the value before the writer writes it, or the writer writes the value and the reader reads it. Timing decides which one will happen. – Kayaman Mar 22 '18 at 12:33