Is reference update thread safe?

后端 未结 6 515
野趣味
野趣味 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:02

    No, this is not thread safe. (What makes you think it is?)

    If you are updating a variable in one thread and reading it from another, you must establish a happens-before relationship between the write and the subsequent read.

    In short, this basically means making both the read and write synchronized (on the same monitor), or making the reference volatile.

    Without that, there are no guarantees that the reading thread will see the update - and it wouldn't even be as simple as "well, it would either see the old value or the new value". Your reader threads could see some very odd behaviour with the data corruption that would ensue. Look at how lack of synchronization can cause infinite loops, for example (the comments to that article, especially Brian Goetz', are well worth reading):

    The moral of the story: whenever mutable data is shared across threads, if you don’t use synchronization properly (which means using a common lock to guard every access to the shared variables, read or write), your program is broken, and broken in ways you probably can’t even enumerate.

提交回复
热议问题