Example of a memory consistency error when using volatile keyword?

后端 未结 2 519
醉梦人生
醉梦人生 2021-02-15 15:47

From docs:

Using volatile variables reduces the risk of memory consistency errors

But this means that sometimes volatile variables

2条回答
  •  迷失自我
    2021-02-15 16:25

    Volatile does the following:

    - It prevents the caching the values in the Thread.

    - It makes sure that the threads having the copies of the values of the fields of the object reconcile with the main copy present in the memory.

    - Making sure the data is written directly to the memory and read from memory itself.

    ## But the condition where volatile fails:

    - Making a Non-Atomic statement Volatile.

    Eg:

    int count = 0;
    
    count++;  // Increment operator is Not Atomic in java
    

    ## Better option:

    1. Its always better to follow the Brian's Rule:

    When ever we write a variable which is next to be read by another thread, or when we are reading a variable which is written just by another thread, it needs to be synchronized. The shared fields must be made private, making the read and write methods/atomic statements synchronized.

    2. Second option is using the Atomic Classes, like AtomicInteger, AtomicLong, AtomicReference, etc.

    ## See this link, i have asked a similar question like yours:

    Why Volatile is behaving weirdly

提交回复
热议问题