What is the problem with volatile with Long and Double types?
sobes.tech AI
Answer from AI
The issue with using volatile for Long and Double types in Java is related to the fact that these types occupy 64 bits and operations on them are not atomic on 32-bit platforms.
Before Java 5, reading and writing 64-bit variables (long and double) were not guaranteed to be atomic, even if declared volatile. This could lead to a situation where, during concurrent access from different threads, a 'half-complete' value is obtained (for example, the high half from one value and the low half from another).
Starting with Java 5, the language specification guarantees atomicity of reading and writing volatile long and double, but if an older JVM version or a non-standard platform is used, the problem may persist.
Therefore, for safe operation with such types in a multithreaded environment, it is recommended to use classes from java.util.concurrent.atomic (such as AtomicLong) or synchronization.