当锁包含非最终对象时,该对象的引用是否仍可以由另一个线程更改? [英] When a lock holds a non-final object, can the object's reference still be changed by another thread?

查看:77
本文介绍了当锁包含非最终对象时,该对象的引用是否仍可以由另一个线程更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当需要同步对象时,IDE会抱怨是否未将其设置为非最终值(因为其引用不是持久性的):

When an object needs to be synchronized, the IDE complains if it's not set non-final (because its reference isn't persistent):

private static Object myTable;
....

synchronized(myTable){          //IDE complains!
     //access myTable here...
}

我们都知道,如果持有锁的线程更改了非最终对象的引用,IDE会抱怨阻止另一个线程进入受保护的块.

We all know the IDE complains to prevent another thread from entering the guarded block if the thread holding the lock changes the non-final object's references.

但是当线程A持有同一个对象的锁时,另一个线程B是否也可以更改同步对象的引用?

But could a synchronized object's reference also be changed by another thread B while thread A holds the lock for the same object?

推荐答案

但是当线程A持有同一个对象的锁时,另一个线程B是否也可以更改同步对象的引用?

But could a synchronized object's reference also be changed by another thread B while thread A holds the lock for the same object?

如果您的意思是可以让另一个线程更改myTable变量的值,则答案是绝对" ...假设有一个允许这样做的代码路径.这是一个私有变量,因此您应该能够找到所有可以更改该值的代码.

If you mean "could another thread change the value of the myTable variable, the answer is "absolutely"... assuming there's a code path that would allow that. It's a private variable, so you should be able to find all the code that can change the value.

持有锁只会阻止另一个线程获取相同的锁.它对什么代码本身可以访问哪些变量没有任何影响.

Holding a lock just stops another thread from acquiring the same lock. It doesn't have any effect on what code can access which variables, in itself.

作为旁注,区分对象变量和变量的值(它是引用,而不是对象)很重要. .因此,没有最终对象"之类的东西-只有变量(以及类和方法)可以是最终的.同样,没有同步对象"之类的东西,并且您不能更改对象的引用"-您可以更改变量的值,使其成为对另一个对象的引用.当您在思考这里发生的事情时,在头脑中弄清楚这些区别可能会有所帮助.

As a side-note, it's important to differentiate between an object, a variable, and the value of the variable (which is a reference, not an object). So there's no such thing as a "final object" - only variables (and classes and methods) can be final. Likewise there's no such thing as a "synchronized object", and you can't change an "object's reference" - you can change the value of a variable so that it's a reference to a different object. Making these distinctions clear in your mind may help you when thinking about what's going on here.

这篇关于当锁包含非最终对象时,该对象的引用是否仍可以由另一个线程更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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