4

The Head First design patterns book mentions singletons and class loaders.

Question : What about class loaders? I heard there is a chance that two class loaders could each end up with their own instance of Singleton.

Answer : Yes, that is true as each class loader defines a namespace. If you have two or more class loaders, you can load the same class multiple times (once in each classloader). Now, if that class happens to be a Singleton, then since we have more than one version of the class, we also have more than one instance of the Singleton. So, if you are using multiple classloaders and Singletons, be careful. One way around this problem is to specify the classloader yourself.

In which situation do Java developers need to have multiple class loaders ? In which situations would multiple class loaders be a problem for singletons ?

Tom Joe
  • 97
  • 7
  • 3
    Middle ware applications frequently have multiple class loaders. In the situation that multiple applications are deployed with dependencies that conflict with those provided by an application server; more commonly, application A includes `apache-log4j-2.13.1` - application B includes `apache-log4j-2.10` and the application server includes `apache-log4j-2.9` (I made the version numbers up). The application server "wins". Note this book is now outdated, as Java 9 introduces modules and obviates this kind of dependency management. – Elliott Frisch Mar 03 '20 at 21:26
  • 1
    @ElliottFrisch I've never come across a system like that. Do you have any non-esoteric examples? – daniu Mar 03 '20 at 21:29
  • 2
    Depends on how you define esoteric. You can [write your own `ClassLoader`](https://www.journaldev.com/349/java-classloader#java-custom-classloader-example), perhaps because you need to [manipulate bytecode](https://asm.ow2.io/). If your application does not use multiple classloaders, why are you worried about it? Also, the most common way to implement a `Singleton` these days is an `enum` (as I said, that book is a bit outdated). – Elliott Frisch Mar 03 '20 at 21:35
  • related: https://stackoverflow.com/questions/39533902/java-singleton-usage-with-multiple-class-loaders – jaco0646 Mar 04 '20 at 16:08

0 Answers0