Java Code Geeks

Sunday, October 19, 2008

Singleton is not really a singleton?

Singleton design pattern is one of the oldest pattern which I learn in college. People like me who have migrated to java world from C++ world finds it hard to digest that if we are not very clear, there can be cases when a singleton java class can have more than one instance. There could be multiple reason for this, details can be found under "Sun Developer Site". One of the reason which C++ people might find difficult is that - if one application uses two different class loaders, then you will get two instances of the singleton class (Each class loader represents one unique namespace, so two classes even if they are the same, if gets loaded by two different class loaders, become two distinct instances). If we think about it in Servlet world, the Servlet container decides when to load the singleton class and when to destroy it. If we are not very clear about the way servlet engine is loading the servlet classes, we might end up having two different instances of the singleton class.

No comments: