java Java在构造函数中泄漏了这个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9851813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java leaking this in constructor
提问by Reinard
Why do IDE's complain about "leaking this in constructor"? I've always assumed that it's just bad practice. But I actually never found why it is bad.
为什么 IDE 会抱怨“在构造函数中泄漏这个”?我一直认为这只是不好的做法。但我实际上从未发现它为什么不好。
回答by Péter T?r?k
Leaking the this
reference in the constructor(not controller) is dangerous, especially in a multithreaded environment. This is because the object is not fully constructed until the constructor call finishes. Leaking this
from the constructor thus means that the external world gets access to an object which is not yet fully constructed. This may not necessarily lead to problems in a a single-threaded program (although it is possible, but the problem is much more obvious in this case). But if this
is leaked to other threads, they can actually try to do something with the object before its construction is finished, which leads to subtle and hard to find bugs.
this
在构造函数(不是控制器)中泄漏引用是危险的,尤其是在多线程环境中。这是因为在构造函数调用完成之前,对象并未完全构造。this
因此,从构造函数泄漏意味着外部世界可以访问尚未完全构造的对象。这在单线程程序中不一定会导致问题(虽然有可能,但在这种情况下问题更加明显)。但是如果this
泄漏给其他线程,他们实际上可以在对象构建完成之前尝试对其进行处理,从而导致微妙且难以发现的错误。
回答by scottb
There are few absolutes in life, eg. you must pay taxes ... or ... death is inevitable. But "passing this
out of a constructor is always bad" is -not- one of them.
生活中很少有绝对的东西,例如。你必须纳税……否则……死亡是不可避免的。但是“传递this
出构造函数总是不好的”不是其中之一。
The caveats pointed out by Peter are all apt and valid. It would certainly be problematic to leak this
from a constructor into any method or context in which the reference would become published to unknown or untrusted clients. It is still bad to publish a reference for a not-yet-fully-constructed object to any client code, trusted or not, that operates with the assumption that it will have a view to a valid and consistent object.
彼得指出的警告都是恰当而有效的。this
从构造函数泄漏到任何方法或上下文中肯定会出现问题,在这些方法或上下文中,引用将被发布到未知或不受信任的客户端。将尚未完全构建的对象的引用发布到任何客户端代码(无论可信与否)的引用仍然很糟糕,这些代码在假设它将具有有效且一致的对象视图的情况下运行。
That said, there is absolutely nothing wrong with passing this
from a constructor to a package-private method that performs a common initialization on, say, a group of objects that share a common interface, particularly if that initialization is lengthy or complex.
也就是说,this
从构造函数传递到包私有方法绝对没有错,该方法对共享公共接口的一组对象执行公共初始化,尤其是在初始化冗长或复杂的情况下。
TL;DR: There are certainly some situations in which, in my opinion, it is not only acceptable to pass this
from a constructor, but actually desirable to do so.
TL;DR:在我看来,在某些情况下,this
从构造函数传递不仅是可以接受的,而且实际上是可取的。