Java Concurrency Programming-volatile

Source: Internet
Author: User

I. Volatite Brief INTRODUCTION
The Java language provides a slightly weaker synchronization mechanism, the volatile variable. Used to ensure that updates to variables are notified to other threads, ensuring that new values are immediately synchronized to main memory, and flushed from main memory immediately before each use. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared.
Two. Volatite thread safety?
Volatile variables are immediately visible to all threads, and all writes to volatile variables can immediately be reflected in other threads, in other words: Volatile variables are consistent across threads, so operations based on volatile variables appear to be thread safe. This view is wrong!
Three. Why is Volatite thread unsafe?

[Java]public class volatiletest{public static volatile int i;public static void increase () {   i++;}} [/java]


Javap-c-L Volatiletest.class

[Java]public class Volatiletest {public static volatile int i;public volatiletest (); code:0: aload_01:invokespecial #1//Method java/lang/object. "":() V4:returnLineNumberTable:line 1:0public static void increase (); code:0: getstatic #2//Field i:i, the value of I is taken to the top of the Operation Stack, and the volatile is guaranteed to be correct at this time. 3:iconst_14:iadd//increase, but other threads may have increased the I value a lot at this time 5:p Utstatic #2//Field i:i, the I value of this already out of date is synchronized back to main memory, and I value is destroyed. 8:returnlinenumbertable:line 6:0line 7:8}[/java]


In this sense, volatile is not entirely thread-safe, although volatile variables are atomic when read and saved, but the self-increment and decrement operations are synthesized by multiple operations, which are not atomic operations.

Java Concurrency Programming-volatile

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.