The singleton pattern is one of the most widely used patterns while implementing solutions using the Java language.
This article does not provide details about the Singleton pattern rather provides some of the loopholes, which the designer and developers need to be aware of when implementing the singleton pattern.
1) If the Singleton class is Serializable, multiple object references of the class can be created
2) A Singleton class can be loaded using multiple class loaders in the same JVM
The above two loop holes allows the client programs that request the Singleton object to create multiple object instances in the same JVM which defeats the purpose of a Singleton class.
Issue 1 has been explained below.
Consider the following Singleton class,
Note that the Singleton is Serializable, consider the following client class which invokes the Singleton,
In the above class, a singleton instance is obtained and assigned to the “originalSingleton” variable.
Since the Singleton object is Serializable, the client writes the object out to an ObjectOutputStream and reads it back.
The read object is then assigned to a new variable called as “hackedSingletonCopy”.
Since Serialized objects are passed by value, the object is deep copied when reading back from the stream which results in two objects being created.
The same process can be repeated to create the desired number of objects defeating the Singleton pattern.
The output of the program would be
Thea1
Thea2
false
which shows that there are more than one instance. Hence the fix is as below.
Override
readResolve method in Singleton as in the below screen shot.
Watch this space for implementation example of Issue 2.....