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

查看:33
本文介绍了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.

推荐答案

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

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天全站免登陆