This article is a mirror article of machine translation, please click here to jump to the original article.

View: 14222|Reply: 0

[Communication] Insight into the basic types of Java and I++ thread security

[Copy link]
Posted on 4/5/2015 10:17:45 PM | | |

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.




Previous:SQL 2008 prompts with an error message (provider: SQL Network Interfaces, error: 25 - Connection word).
Next:[Fast and Furious 7] debuts 2.12G DVD The clearest version on the Internet
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com