1 7 8 package org.dom4j.util; 9 10 import java.lang.ref.WeakReference ; 11 12 23 24 public class PerThreadSingleton implements SingletonStrategy { 25 private String singletonClassName = null; 26 27 private ThreadLocal perThreadCache = new ThreadLocal (); 28 29 public PerThreadSingleton() { 30 } 31 32 public void reset() { 33 perThreadCache = new ThreadLocal (); 34 } 35 36 public Object instance() { 37 Object singletonInstancePerThread = null; 38 WeakReference ref = (WeakReference ) perThreadCache.get(); 40 if (ref == null || ref.get() == null) { 43 Class clazz = null; 44 try { 45 clazz = Thread.currentThread().getContextClassLoader().loadClass( 46 singletonClassName); 47 singletonInstancePerThread = clazz.newInstance(); 48 } catch (Exception ignore) { 49 try { 50 clazz = Class.forName(singletonClassName); 51 singletonInstancePerThread = clazz.newInstance(); 52 } catch (Exception ignore2) { 53 } 54 } 55 perThreadCache.set(new WeakReference (singletonInstancePerThread)); 56 } else { 57 singletonInstancePerThread = ref.get(); 58 } 59 return singletonInstancePerThread; 60 } 61 62 public void setSingletonClassName(String singletonClassName) { 63 this.singletonClassName = singletonClassName; 64 } 65 66 } 67 68 104 | Popular Tags |