Stale value of Shared variable

后端 未结 4 435
青春惊慌失措
青春惊慌失措 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: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.

提交回复
热议问题