Stale value of Shared variable

后端 未结 4 415
青春惊慌失措
青春惊慌失措 2021-01-06 08:38

While reading Concurrency in practice I read that:

NoVisibility demonstrated one of the ways that insufficiently synchronized programs can c

相关标签:
4条回答
  • 2021-01-06 08:44

    It's not Java specific issue. Processors have caches. Without synchronization processor 1 can read a value into its cache from memory, modify it in its cache but never flush it, then processor 2 reads stale value from memory

    0 讨论(0)
  • 2021-01-06 08:45

    Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory. The volatile keyword is used to say to the jvm "Warning, this variable may be modified in an other Thread". Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile force the thread to update the original variable for each variable.

    Source DZone

    Hardware Implementation

    This happens due to the processor optimizations that are done for fast access of variables. When the variable is kept in the cache then it is much faster to access than going to memory everytime. So for flushing the cache you need to say volatile go and flush the cache and rebuild it as this variable is being modified in other thread.

    The caching of static variables is also done, they too are a eligible for caching due to same reason fast access. So yes you need volatile for static variables too.

    See also:

    What does volatile do?

    0 讨论(0)
  • 2021-01-06 08:55

    This issue is related to memory visibility issue of Multithreading.

    If you want to read/get value of an object which can be modified by multiple threds; then you need to be careful. Let's take a sample example to stress the point :

    public class XYZ{
       private String state;
    
       public synchronized setState(..){
          //set state
       } 
       public String getState(){
          return state;
       }
    

    }

    Above example doesn't synchronize the getter method which returns the state. So you might get the stale data (even if its static)

    Only way to get latest data is either you syncronize the get method or declare state as volatile.

    0 讨论(0)
  • 2021-01-06 09:02

    It's saying that in main the intention is to set number=42 and ready=true at the same time, but since they were called in this particular order there is a race condition with your ReaderThread where it could (probably will) print out the number even though we really don't want it to.

    They would like you to synchronize those 2 variables to be set together.

    0 讨论(0)
提交回复
热议问题