Is reference update thread safe?

后端 未结 6 513
野趣味
野趣味 2021-01-26 13:49
public class Test{
   private MyObj myobj = new MyObj(); //it is not volatile


   public class Updater extends Thred{
      myobje = getNewObjFromDb() ; //not am settin         


        
6条回答
  •  北海茫月
    2021-01-26 14:15

    Volatile would work for boolean variables but not for references. Myobj seems to perform like a cached object it could work with an AtomicReference. Since your code extracts the value from the DB I'll let the code stay as is and add the AtomicReference to it.

    import java.util.concurrent.atomic.AtomicReference;
    
        public class AtomicReferenceTest {
            private AtomicReference myobj = new AtomicReference();
    
            public class Updater extends Thread {
    
                public void run() {
                    MyObj newMyobj = getNewObjFromDb();
                    updateMyObj(newMyobj);
                }
    
                public void updateMyObj(MyObj newMyobj) {
                    myobj.compareAndSet(myobj.get(), newMyobj);
                }
    
                 }
            public MyObj getData() {
                 return myobj.get();
            }
        }
    
        class MyObj {
        }
    

提交回复
热议问题