In Java, the other basic variables are atomic, except for the 8-byte, 64-bit variables of Long and Double.
The Java storage model requires both get and store operations to be atomic, but for non-volatile long and double variables, the JVM allows splitting a 64-bit read or write into two 32-bit operations.
If the read and write occur on different threads, reading a non-volatile type long may result in a high 32 bits of one value and a low 32 bits of the other.
So even if you don't care about expired data, it may not be safe to use shared, mutable long and double variables in a multithreaded program unless they are declared volatile, or protected with a lock.
Speaking of atomic operations, it means that reading and writing are atomic, such as i=5; This is an atomic operation.
However, if the operation of two atoms is carried out together, it is not necessarily atomic, such as reading first and then writing, then it is possible that the variable has been modified after reading.
i++ is such an operation, read first and then write, so the integer variable is atomic, not that i++ is an atomic operation.
When you use for(int i=0; i<10000; i++){System.out.print(i)}
You will find that i will not print 10,000 in the end, and print about 8-9 thousand.
But in the case of multi-threading, even if the integer variable is atomic, there may be thread safety problems, which is a thread visibility problem, so you need to add a volatile statement.
This modifier is a forced variable that is read from memory each time and is not stored in registers. |