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
This will get only loaded once when the class is loaded by the classloader. This example provides a better Singleton implementation however, it's as lazy-loaded as possible and thread-safe. Moreover, it works in all known versions of Java. This solution is the most portable across different Java compilers and virtual machines.
public class Single {
private static class SingleHolder {
private static final Single INSTANCE = new Single();
}
private Single() {
...load properties...
}
public static Single getInstance() {
return SingleHolder.INSTANCE;
}
}
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).