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

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

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