Sunday, April 02, 2006

Java and the Singleton


There is a major problem using the Singleton in java

Classes in java can be garbage collected!

A class can be garbage collected when there are no objects of the class and there are no variable references to the class of the class

If the Logger class is garbage collected then the value of the Singleton will be lost

The next time you reference the Singleton you will get the default value for the Singleton

Solution
Insure that there will be a reference to the class or an instance of the class

Place an instance of the class in a global reference

private static void preventClassGarbageCollection()
{
Properties systemTable = System.getProperties();
systemTable.put( "_$sdsu.logging.Logger.instance",
new Logger());
}
[ref : http://www.eli.sdsu.edu/courses/spring98/cs635/notes/logger/logger.html]

No comments: