Basic types of Java and deep parsing of i++ thread security

Source: Internet
Author: User

In Java, other basic variables are atomic in addition to the 8-byte, 64-bit variables of long and double.


The Java storage model requires both fetch and save operations to be atomic, but for volatile long and double variables, the JVM allows 64-bit reads or writes to be divided into two 32-bit operations.

If read and write occur on a different thread, this situation reads a volatile type long and can appear with a value of 32 bits and a lower 32 bit of another value.

Therefore, even if you don't care about out-of-date data, it may be unsafe to use only shared, variable long and double variables in multithreaded applications, unless you declare them as volatile or protected with a lock.


Speaking of atomic manipulation, it means that reading and writing are atomic, such as i=5; This is an atomic operation.

But two atomic operations are not necessarily atomic, such as reading and writing, and then it is possible that the variable has been modified after the reading.

I++ is such an operation, read and write first, so that the integer variable is atomic, not to say 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 out 10000 at the end, printing out about 8-9 thousand.


However, in the case of multithreading, even if the integer variable is atomic, there may be a thread-safety problem, this is the problem of thread visibility, so need to add volatile declaration to do,

The modifier is a mandatory variable that is read from memory each time and is not stored in registers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.