Object Publication and “This” Reference Escape

Honey Keny Malviya
Agile Architect’s Blog
2 min readMar 12, 2019

--

Making an object available to code outside its scope is called publishing an object. Publishing internal state variables can compromise encapsulation and make it more difficult to preserve invariants. Publishing objects before they are fully constructed can compromise thread safety. An object that is published when it should not have been, is said have escaped.

How to publish an object:

  • Store a reference of the object in a public static field
  • Return the object from a non-private method
  • Passing reference of an object to an alien method — Alien method is the one whose behavior is not fully specified by the invoking class (methods in other classes, overridable methods: neither private nor final).
  • Publish an instance of an inner class — Because inner class contains a hidden reference to the enclosing instance. (escaping this reference)
  • Publishing one object may indirectly publish other (collections)
  • Publishing an object also publishes any objects referred to by its non-private fields

An object is in predictable, consistent state only after its constructor returns. So publishing an object from within its constructor can publish in incompletely constructed object even if the publication in the last statement in the constructor.

“This” Reference Escape:

This reference should not escape from the thread until after the constructor returns. The this reference can be stored somewhere by the constructor so long as it is not used by another thread until after construction.

How can this reference escape:

  • Publishing an instance of inner class, implicitly publishes the enclosing instance as well because inner class instance contains a hidden reference to the enclosing instance. For example, registering an event listener from constructor.
  • Start a thread from within a constructor. When an object creates a thread from its constructor, it almost always shares its this reference with the new thread. Either explicitly, by passing it to the constructor or implicitly, because the Thread or Runnable is an inner class of the owning object. The new thread might then be able to see the owning object before it is fully constructed.

Avoid improper construction of objects by using a private constructor and a public factory method to prevent this reference from escaping.

  • Alien method is the one whose behavior is not fully specified by the invoking class (methods in other classes, overridable methods: neither private nor final).

--

--

Honey Keny Malviya
Agile Architect’s Blog

Agile Software Architect | AI & ML | Java | Spring Boot | Angular 6 | AWS | SCRUM Master