1 22 package org.jboss.util.collection; 23 24 import java.lang.ref.WeakReference ; 25 import java.util.Map ; 26 import java.util.WeakHashMap ; 27 28 40 public abstract class WeakClassCache 41 { 42 43 protected Map cache = new WeakHashMap (); 44 45 51 public Object get(Class clazz) 52 { 53 if (clazz == null) 54 throw new IllegalArgumentException ("Null class"); 55 56 Map classLoaderCache = getClassLoaderCache(clazz.getClassLoader()); 57 58 WeakReference weak = (WeakReference ) classLoaderCache.get(clazz.getName()); 59 if (weak != null) 60 { 61 Object result = weak.get(); 62 if (result != null) 63 return result; 64 } 65 66 Object result = instantiate(clazz); 67 68 weak = new WeakReference (result); 69 classLoaderCache.put(clazz.getName(), weak); 70 71 generate(clazz, result); 72 73 return result; 74 } 75 76 84 public Object get(String name, ClassLoader cl) throws ClassNotFoundException 85 { 86 if (name == null) 87 throw new IllegalArgumentException ("Null name"); 88 if (cl == null) 89 throw new IllegalArgumentException ("Null classloader"); 90 Class clazz = cl.loadClass(name); 91 return get(clazz); 92 } 93 94 100 protected abstract Object instantiate(Class clazz); 101 102 108 protected abstract void generate(Class clazz, Object result); 109 110 116 protected Map getClassLoaderCache(ClassLoader cl) 117 { 118 synchronized (cache) 119 { 120 Map result = (Map ) cache.get(cl); 121 if (result == null) 122 { 123 result = CollectionsFactory.createConcurrentReaderMap(); 124 cache.put(cl, result); 125 } 126 return result; 127 } 128 } 129 } 130 | Popular Tags |