Java在构造函数中泄漏了这个 [英] Java leaking this in constructor

查看:120
本文介绍了Java在构造函数中泄漏了这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么IDE会抱怨在构造函数中泄露这个?我一直认为这只是不好的做法。但我实际上从来没有发现为什么它是坏的。

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.

推荐答案

泄漏这个 构造函数(非控制器)中的引用是危险的,尤其是在多线程环境中。这是因为在构造函数调用完成之前,对象尚未完全构造。从构造函数泄漏因此意味着外部世界可以访问尚未完全构造的对象。这可能不一定会导致单线程程序出现问题(尽管有可能,但在这种情况下问题更加明显)。但是如果这个泄漏给其他线程,他们实际上可以尝试在构造完成之前对该对象做一些事情,这会导致细微且难以发现的错误。

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.

这篇关于Java在构造函数中泄漏了这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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