Class SingletonHolder<T>
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 Summary
Constructors -
Method Summary
-
Constructor Details
-
SingletonHolder
public SingletonHolder()
-
-
Method Details
-
createInstance
implement to return an instance of type T- Returns:
-
get
- Returns:
- instance of type T
-
init
callsget()
to obtain an instance eagerly, otherwise will create instance lazily on a firstget()
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.
-