I ran into an unusual error while working on my project. To better learn from and remember it, I'd like to know if this type of error has a name or some definition. (The error itself OutOfMemoryError isn't unusual, I'm talking about what lead to this error).
My (simplified) situation was this:
I had a class Singleton:
class Singleton extends ClassA{
private static Singleton instance;
private Singleton(){ // implicitly calls super() }
public static Singleton getInstance(){
if (instance==null) instance = new Singleton();
return instance;
}
}
And it's superclass ClassA:
abstract class ClassA{
public ClassA(){
ClassB objectB = new ClassB();
// .. some logic ..
}
}
And a class ClassB that uses Singleton in it's constructor:
class ClassB{
public ClassB(){
Singleton singleton = Singleton.getInstance();
// .. some logic ..
}
}
What happens is the following:
1- ClassB is instantiated somewhere. It's constructor is invoked and calls Singleton.getInstance().
2- Singleton.getInstance() sees that instance == null and executes instance = new Singleton().
3- The constructor of Singleton is run. It's empty, but it implicitly calls the superclass' (ClassA) constructor.
4- The superclass of Singleton instantiates a ClassB object new ClassB().
5- ClassB's constructor is invoked and calls Singleton.getInstance()...
Since the instantiation of instance in Singleton never reached it's finish, instance == null still returns true, and the cycle never ends.
Resulting in an infinite loop, that finally resulted in an OutOfMemoryError.
So my question is: is this kind of infinite-loop-with-singletons error a common issue? Any ideas how I can avoid it in the future?