Java thread (16): volatile keyword

Source: Internet
Author: User

Java™The language includes two internal synchronization mechanisms: Synchronous block (or method) and volatile variables. Both mechanisms are proposed to achieve code thread security. Among them, the synchronization of Volatile variables is poor (but sometimes it is simpler and has lower overhead), and its usage is more error-prone. When talking about the volatile keyword, I have to mention one article: Java Theory and Practice: Correct Use of Volatile variables. This article elaborates on the usage of volatile keywords. The reason why volatile is not commonly used is that this keyword is also very important in high-performance multi-threaded programs, but this keyword may cause many problems. First, let's consider a question: why does variable need volatile to be modified? To clarify this problem, we should first understand what is done inside the computer. For example, after performing an I ++ operation, the computer performs three internal operations: read, modify, and write. Similarly, a value assignment operation is performed for a long data type. In 32 systems, it takes two steps to complete the assignment. First, modify the low 32 bits, and then modify the high 32 bits. Assume that when you place the preceding operations in a multi-threaded environment, some of these steps are executed, and another thread has referenced the variable value, this leads to the problem of reading dirty data. With this assumption, it is not difficult to understand the volatile keyword. Volatile can be used before any variable, but cannot be used before the final variable, because the final variable cannot be modified. There is no thread security issue.

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.