Java Threads: Volatile keywords

Source: Internet
Author: User
Tags final thread volatile

Talk about the Volatile keyword, had to mention an article is: "Java Theory and Practice: The correct use of Volatile variables," This article on the use of Volatile keyword is very incisive exposition.

The reason why we want to separate volatile is that this keyword is also important in high-performance multithreaded programs, but this keyword is not good enough to be a problem.

First, consider a question: why do variables need volatile to be modified?

To figure this out, you should first understand what is going on inside the computer. For example, do a i++ operation, the computer did three times processing: read-Modify-write.

Similarly, for a long data, the assignment operation, in 32 system need to go through two steps to complete, first modify the lower 32 digits, and then modify the high 32 bits.

Suppose that when you put the above actions in a multithreaded environment, the problem that may arise is that the steps are executed, and the other thread already references the value of the variable, causing the problem of reading dirty data.

Through this idea, it is not difficult to understand the volatile keyword.

Volatile can be used in front of any variable, but not in front of final variables, because final-type variables are forbidden to be modified. There is also no thread-safe problem.

For more information, see:: "Java Theory and Practice: Using the Volatile variable correctly," wrote very well.

Source: http://lavasoft.blog.51cto.com/62575/222076

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.