Search code examples
javaconstructorinitializationthread-safety

How does "this" escape the constructor in Java?


I've heard about this happening in non thread-safe code due to improperly constructed objects but I really don't have the concept down, even after reading about in in Goetz's book. I'd like to solidify my understanding of this code smell as I maybe doing it and not even realize it. Please provide code in your explanation to make it stick, thanks.


Solution

  • Really simple example:

    public class Test
    {
        private static Test lastCreatedInstance;
    
        public Test()
        {
            lastCreatedInstance = this;
        }
    }