Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this Java singleton get rebuilt repeatedly in WebSphere 6?

I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty):

...
if(Single.getInstance().firstTime()){
   doPreperations();
}
normalResponse();
...

The singleton 'Single' looks like this:

private static Single theInstance = new Single();

private Single() {
...load properties...
}

public static Single getInstance() {
    return theInstance;
}

With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again?

PS - We're running WebSphere 6 with the App on Java 1.4

like image 627
Adam Avatar asked Oct 22 '08 14:10

Adam


1 Answers

I found this on Sun's site:

Multiple Singletons Simultaneously Loaded by Different Class Loaders

When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance. That is particularly relevant in servlets running in certain servlet engines (iPlanet for example), where each servlet by default uses its own class loader. Two different servlets accessing a joint Singleton will, in fact, get two different objects.

Multiple class loaders occur more commonly than you might think. When browsers load classes from the network for use by applets, they use a separate class loader for each server address. Similarly, Jini and RMI systems may use a separate class loader for the different code bases from which they download class files. If your own system uses custom class loaders, all the same issues may arise.

If loaded by different class loaders, two classes with the same name, even the same package name, are treated as distinct -- even if, in fact, they are byte-for-byte the same class. The different class loaders represent different namespaces that distinguish classes (even though the classes' names are the same), so that the two MySingleton classes are in fact distinct. (See "Class Loaders as a Namespace Mechanism" in Resources.) Since two Singleton objects belong to two classes of the same name, it will appear at first glance that there are two Singleton objects of the same class.

Citation.

In addition to the above issue, if firstTime() is not synchronized, you could have threading issues there as well.

like image 178
Chris Marasti-Georg Avatar answered Sep 27 '22 21:09

Chris Marasti-Georg