Java leaking this in constructor [duplicate]

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.

Leave a Comment