Class SingletonHolder<T>

java.lang.Object
de.businesscode.util.SingletonHolder<T>

public abstract class SingletonHolder<T> extends Object

this singleton-holder helper should be used in container environments to prevent class loader leaking, implementation currently does not use java's WeakReferences or SoftReferences to reference the instances, rather is uses strong references via Maps keyed by the class-name string. We could use WeakReference which would be garbage collected properly, but this is against the usual Singleton idea to save start-up costs, as it would cause to re-create such costly "singletons" many times during container webapp lifecycle. If the singletons are managed by this holder, it is ensured, that all singleton references are dropped once the webapp is shut down. The BcdUiApplicationContextListener takes care of this and calls clear() method.

usage example:

 class MySingleton {
   private static SingletonHolder<MySingleton> holder = new SingletonHolder<>() {
     createInstance() {
       return new MySingleton();
     }
   }.init(); // optionally, otherwise the instantiation would be lazy
 
   static MySingleton getInstance() {
     return holder.get();
   }
 }
 

Future note: this implementation *can* be extended to support native SoftReferences or WeakReferences i.e. via a constructor switch or subclsses which would maybe suit more the non-costly singletons being re-created and cleaned-up many times during typical webapp lifecycle.

Since:
4.5.6
  • Constructor Details

    • SingletonHolder

      public SingletonHolder()
  • Method Details

    • createInstance

      protected abstract T createInstance()
      implement to return an instance of type T
      Returns:
    • get

      public T get()
      Returns:
      instance of type T
    • init

      public SingletonHolder<T> init()
      calls get() to obtain an instance eagerly, otherwise will create instance lazily on a first get() call
      Returns:
    • clear

      public static void clear()
      calling THIS method clears all references to singleton instances allowing GC to collect them causing to re-create instances on next access.