mardi 3 mars 2020

Design patterns - Singleton and class loaders

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 ?

Aucun commentaire:

Enregistrer un commentaire