Synchronizing on an object in java, then changing the value of the synchronized-on variable(在java中同步一个对象,然后更改同步变量的值)
问题描述
我遇到了这样的代码
synchronized(obj) {
obj = new Object();
}
感觉有些不对劲,我无法解释,这段代码是OK还是真的有什么问题,请指出.谢谢
Something does not feel right about this , I am unable to explain, Is this piece of code OK or there is something really wrong in it, please point it out. Thanks
推荐答案
这可能不是你想做的.您正在对不再持有引用的对象进行同步.考虑另一个运行此方法的线程:在对 obj
的引用被更新为指向新对象之后,它们可能会进入并尝试锁定.那时,它们正在与第一个线程不同的对象上进行同步.这可能不是您所期望的.
It's probably not what you want to do. You're synchronizing on an object that you're no longer holding a reference to. Consider another thread running this method: they may enter and try to hit the lock at the moment after the reference to obj
has been updated to point to the new object. At that point, they're synchronizing on a different object than the first thread. This is probably not what you're expecting.
除非您有充分的理由不这样做,否则您可能希望在最终对象上进行同步(为了可见性).在这种情况下,您可能希望使用单独的锁定变量.例如:
Unless you have a good reason not to, you probably want to synchronize on a final Object (for visibility's sake.) In this case, you would probably want to use a separate lock variable. For example:
class Foo
{
private final Object lock = new Object();
private Object obj;
public void method()
{
synchronized(lock)
{
obj = new Object();
}
}
}
这篇关于在java中同步一个对象,然后更改同步变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中同步一个对象,然后更改同步变量的值
基础教程推荐
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01