参考更新线程安全吗? [英] Is reference update thread safe?

查看:87
本文介绍了参考更新线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test{
   private MyObj myobj = new MyObj(); //it is not volatile


   public class Updater extends Thred{
      myobje = getNewObjFromDb() ; //not am setting new object
   }

   public MyObj getData(){
    //getting stale date is fine for 
    return myobj;
   }


}

定期更新更新myobj

其他类使用getData获取数据

这段代码线程安全而不使用volatile关键字?

我想是的。有人可以确认吗?

Updated regularly updates myobj
Other classes fetch data using getData
IS this code thread safe without using volatile keyword?
I think yes. Can someone confirm?

推荐答案

,这不是线程安全的。 (你认为它是什么?)

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.

简而言之,这基本上意味着同时使读取和写入同步(在同一台显示器上)或制作引用 volatile

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

没有它,不能保证读取线程会看到更新 - 它不会甚至就像好吧,它会看到旧值或新值一样简单。您的读者线程可能会看到一些非常奇怪的行为,随之而来的是数据损坏。看看缺乏同步会导致无限循环,例如(对该文章的评论,特别是Brian Goetz',非常值得一读):

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.

这篇关于参考更新线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆