Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The problem with this pattern is that is created it creates a hard reference to a class instance into the class itself. As long as this instance is not released, the class will not be unloadable. At the end, this leads to the server being unable to reclaim the space for the entire webapp class loader.

Workaround 1

This workaround is for the case this class should be shared between webapps, or if the server must contain only one webapp. That is, we need to used the same instance across several webapps in the same server, or there is no need to worry about it. In this case, the class will need to be deployed on a shared classloader. This means this class must be in the shared/lib or shared/classes directory.

There is not a problem in this case, because This way, the class will be loaded by a parent classloader, and not by the webapp classloader itself, so no resources need to be reclaimed.This is considered a workaround for the case in which your server has a single webapp. You can put your class, and all the classes it depends on, in the shared/classes directory, and it will not be a memory leak source anymore.

Workaround 2

If you need to have a singleton instance for each webapp, you could use commons-discovery. This library provides a class named DiscoverSingleton that can be used to implement singletons in your webapp.

...

But only this does not make for a workaround. The most important advantage is the DiscoverSingleton.release() method, that releases all references to instantiated singletons in the current classloader. A call to this method could be placed into a ServletContextListener, into its contextDestroyed() method.

...

we could release all cached references to the instantiated singletons. Of course, this listener should be registered on the web.xml descriptor before any other listener that could use a singleton.