Sunday, 5 February 2017

Object Escape

This issue tensed all of my team mates for almost 10 days in production. For me just luck to identified and fixed in production. It was very difficult for us (40 developer) to reproduce it.
Hope this may helpful to others too.


Object Escape
     Object is said to be escaped, when it published before it not supposed to publish.
Publishing object means, make it available outside its scope.

Object is constructed by calling its constructor, but object is available before completion of constructor.


Lets look at following example, how class B is escaped.

Class A {
   public B b;
}

Class B {
   B(A a) {
      a.b = this;
      //Some other Operation
   }
}

public static void main(String[] args) {
   A a =  new A();
   B b = new B(a);
   // Object is b escaped
   //Some other thread can get B value before it constructor done
   // By calling a.b
}

Thumb rule is do not escape this reference from constructor.
Class B can broken if multiple thread is using A reference, can cause damage, usually not reproducible.

One of Safest Way avoid Object Escaping is to use factory method as shown below

class B {
   private B() {
   }

   public static B newInstance(A a) {
      B b = new B();//Constructor is completed
      a.b = b;
   }
}