org.dom4j.util
public class: PerThreadSingleton [javadoc |
source]
java.lang.Object
org.dom4j.util.PerThreadSingleton
All Implemented Interfaces:
SingletonStrategy
PerThreadSingleton is an implementation of the
SingletonStrategy used to provide common factory access to a single object
instance based on an implementation strategy for one object instance per
thread. This is useful in replace of the ThreadLocal usage.
- author:
< - a href="mailto:ddlucas@users.sourceforge.net">David Lucas
- version:
$ - Revision: 1.3 $
| Method from org.dom4j.util.PerThreadSingleton Detail: |
public Object instance() {
Object singletonInstancePerThread = null;
// use weak reference to prevent cyclic reference during GC
WeakReference ref = (WeakReference) perThreadCache.get();
// singletonInstancePerThread=perThreadCache.get();
// if (singletonInstancePerThread==null) {
if (ref == null || ref.get() == null) {
Class clazz = null;
try {
clazz = Thread.currentThread().getContextClassLoader().loadClass(
singletonClassName);
singletonInstancePerThread = clazz.newInstance();
} catch (Exception ignore) {
try {
clazz = Class.forName(singletonClassName);
singletonInstancePerThread = clazz.newInstance();
} catch (Exception ignore2) {
}
}
perThreadCache.set(new WeakReference(singletonInstancePerThread));
} else {
singletonInstancePerThread = ref.get();
}
return singletonInstancePerThread;
}
|
public void reset() {
perThreadCache = new ThreadLocal();
}
|
public void setSingletonClassName(String singletonClassName) {
this.singletonClassName = singletonClassName;
}
|