• Post Reply Bookmark Topic Watch Topic
  • New Topic

leaking references?  RSS feed

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the line
instances.add(this);to your constructor.
But then other threads can use instances to access the object before construction of the object is complete."

Sourced from here.

How?
 
Stephan van Hulst
Saloon Keeper
Posts: 7986
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would make that statement even stronger: Always avoid passing 'this' as an argument to a method, during execution of a constructor.

The reason is that during the execution of the constructor, 'this' is still in an inconsistent state. It's still being constructed. If you pass an inconsistent object to other parts of the program, unexpected things may happen.

Of course, if you can prove that 'this' is in a consistent state at some point during execution of the constructor, you're free to pass it around. Note that this can only be the case when the class is not extensible, i.e., when it's either final or has a private constructor.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!