在java中同步一个对象,然后改变synchronized-on变量的值 [英] Synchronizing on an object in java, then changing the value of the synchronized-on variable

查看:16
本文介绍了在java中同步一个对象,然后改变synchronized-on变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这样的代码

synchronized(obj) {

   obj = new Object();

}

感觉有些不对,我无法解释,这段代码是否正常或确实有什么问题,请指出.谢谢

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中同步一个对象,然后改变synchronized-on变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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