At the interview, the question was asked: "What are the requirements for volatile variables?". Those. why all this is necessary and what makes it clear, but regarding the requirements I could not find a concrete answer.

  • Maybe it meant? Those. perhaps in this context, this means that if you mark a variable as volatile, it means .... and you need to use it in order .... - Chubatiy
  • 3
    Well, if you look in jls, then volatile can only be fields that are not marked as final . In other cases, and in general, there is no sense - local variables are not divided between threads, and final fields do not change. - zRrr
  • @zRrr, volatile provides (including) a ban on reordering processor operations. I really wanted to say that it follows from this that it may also be necessary for local variables, but I could not think of an example ... But java has life on dubious processor architectures :) - Qwertiy
  • one
    @Qwertiy, it seems to me, in the case of a single thread, jvm should generate instructions, the visible result of which should correspond to the one described in jls (it contains the order of execution, calculation of arguments, etc.), i.e. The programmer should not bother with this. In the case of multiple threads, so that volatile guaranteed to have an effect, there must be a pair of volatile write -> volatile read. In general, barriers in java can be used via Unsafe / VarHandles in JDK 9. - zRrr

1 answer 1

If 2 threads read and write to a variable, then using only volatile not enough. You must also use synchronization to ensure read and write atomicity. More because of the volatile performance suffers, because the value is written \ read immediately into memory, bypassing the caches, and it is expensive. That is, you should not use volatile in places where performance is important.