在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();
        }
    }
}

相关文章