Sunday, March 09, 2008

Java : Inner Classes and Parent Reference Escaping

When an inner class is created inside a class in java, it transparently contains a reference to its parent class. If by chance this reference leaks out , it compromises the thread safety of the parent class. To avoid these kind of issues , factory methods should be used to create inner classes .

Another thing that should be best avoided is : starting of a thread inside the constructor of a class.
Since the thread object also shares the reference to its parent class, this reference might be in an inconsistent state when the thread is started .

To prevent these type of scenarios factory methods are best.

e.g

public class Prent {

private childThread;

private Parent(){
childThread = new Thread();
}

public static Parent newInstance(){
Parent parent = new Parent();
childThread.start();
return parent
}

}

No comments: