Java leaking this in constructor

Reinard picture Reinard · Mar 24, 2012 · Viewed 17.3k times · Source

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.

Answer

Péter Török picture Péter Török · Mar 24, 2012

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.