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.
|
1 answer
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.
|
volatilecan only be fields that are not marked asfinal. In other cases, and in general, there is no sense - local variables are not divided between threads, andfinalfields do not change. - zRrrvolatileguaranteed 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