You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClassLoaderRepository.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package org.aspectj.apache.bcel.util;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2001 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <http://www.apache.org/>.
  54. */
  55. import java.io.IOException;
  56. import java.io.InputStream;
  57. import java.lang.ref.Reference;
  58. import java.lang.ref.ReferenceQueue;
  59. import java.lang.ref.SoftReference;
  60. import java.net.URL;
  61. import java.net.URLClassLoader;
  62. import java.util.AbstractMap;
  63. import java.util.Collections;
  64. import java.util.HashMap;
  65. import java.util.Map;
  66. import java.util.Set;
  67. import java.util.WeakHashMap;
  68. import org.aspectj.apache.bcel.classfile.ClassParser;
  69. import org.aspectj.apache.bcel.classfile.JavaClass;
  70. /**
  71. * The repository maintains information about which classes have
  72. * been loaded.
  73. *
  74. * It loads its data from the ClassLoader implementation
  75. * passed into its constructor.
  76. *
  77. * @see org.aspectj.apache.bcel.Repository
  78. *
  79. * @version $Id: ClassLoaderRepository.java,v 1.8 2006/08/21 15:23:58 aclement Exp $
  80. * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
  81. * @author David Dixon-Peugh
  82. */
  83. public class ClassLoaderRepository implements Repository {
  84. private static java.lang.ClassLoader bootClassLoader = null;
  85. private java.lang.ClassLoader loader;
  86. // Choice of cache...
  87. private WeakHashMap /*<URL,SoftRef(JavaClass)>*/localCache = new WeakHashMap();
  88. private static SoftHashMap /*<URL,JavaClass>*/sharedCache = new SoftHashMap(Collections.synchronizedMap(new HashMap()));
  89. // For fast translation of the classname *intentionally not static*
  90. private SoftHashMap /*<String,URL>*/ nameMap = new SoftHashMap(new HashMap(), false);
  91. public static boolean useSharedCache =
  92. System.getProperty("org.aspectj.apache.bcel.useSharedCache","true").equalsIgnoreCase("true");
  93. private static int cacheHitsShared = 0;
  94. private static int missSharedEvicted = 0; // Misses in shared cache access due to reference GC
  95. private long timeManipulatingURLs = 0L;
  96. private long timeSpentLoading = 0L;
  97. private int classesLoadedCount = 0;
  98. private int misses = 0;
  99. private int cacheHitsLocal = 0;
  100. private int missLocalEvicted = 0; // Misses in local cache access due to reference GC
  101. public ClassLoaderRepository( java.lang.ClassLoader loader ) {
  102. this.loader = (loader != null) ? loader : getBootClassLoader();
  103. }
  104. private static synchronized java.lang.ClassLoader getBootClassLoader() {
  105. if (bootClassLoader == null) {
  106. bootClassLoader = new URLClassLoader(new URL[0]);
  107. }
  108. return bootClassLoader;
  109. }
  110. // Can track back to its key
  111. public static class SoftHashMap extends AbstractMap {
  112. private Map map;
  113. boolean recordMiss = true; // only interested in recording miss stats sometimes
  114. private ReferenceQueue rq = new ReferenceQueue();
  115. public SoftHashMap(Map map) { this.map = map; }
  116. public SoftHashMap() { this(new HashMap()); }
  117. public SoftHashMap(Map map, boolean b) { this(map); this.recordMiss=b;}
  118. class SpecialValue extends SoftReference {
  119. private final Object key;
  120. SpecialValue(Object k,Object v) {
  121. super(v,rq);
  122. this.key = k;
  123. }
  124. }
  125. private void processQueue() {
  126. SpecialValue sv = null;
  127. while ((sv = (SpecialValue)rq.poll())!=null) {
  128. map.remove(sv.key);
  129. }
  130. }
  131. public Object get(Object key) {
  132. SpecialValue value = (SpecialValue)map.get(key);
  133. if (value==null) return null;
  134. if (value.get()==null) {
  135. // it got GC'd
  136. map.remove(value.key);
  137. if (recordMiss) missSharedEvicted++;
  138. return null;
  139. } else {
  140. return value.get();
  141. }
  142. }
  143. public Object put(Object k, Object v) {
  144. processQueue();
  145. return map.put(k, new SpecialValue(k,v));
  146. }
  147. public Set entrySet() {
  148. return map.entrySet();
  149. }
  150. public void clear() {
  151. processQueue();
  152. map.clear();
  153. }
  154. public int size() {
  155. processQueue();
  156. return map.size();
  157. }
  158. public Object remove(Object k) {
  159. processQueue();
  160. SpecialValue value = (SpecialValue)map.remove(k);
  161. if (value==null) return null;
  162. if (value.get()!=null) {
  163. return value.get();
  164. }
  165. return null;
  166. }
  167. }
  168. /**
  169. * Store a new JavaClass into this repository as a soft reference and return the reference
  170. */
  171. private void storeClassAsReference(URL url, JavaClass clazz ) {
  172. if (useSharedCache) {
  173. clazz.setRepository(null); // can't risk setting repository, we'll get in a pickle!
  174. sharedCache.put(url, clazz);
  175. } else {
  176. clazz.setRepository(this);
  177. localCache.put(url, new SoftReference(clazz));
  178. }
  179. }
  180. /**
  181. * Store a new JavaClass into this Repository.
  182. */
  183. public void storeClass( JavaClass clazz ) {
  184. storeClassAsReference(toURL(clazz.getClassName()),clazz);
  185. }
  186. /**
  187. * Remove class from repository
  188. */
  189. public void removeClass(JavaClass clazz) {
  190. if (useSharedCache) sharedCache.remove(toURL(clazz.getClassName()));
  191. else localCache.remove(toURL(clazz.getClassName()));
  192. }
  193. /**
  194. * Find an already defined JavaClass in the local cache.
  195. */
  196. public JavaClass findClass( String className ) {
  197. if (useSharedCache) return findClassShared(toURL(className));
  198. else return findClassLocal(toURL(className));
  199. }
  200. private JavaClass findClassLocal( URL url ) {
  201. Object o = localCache.get(url);
  202. if (o != null) {
  203. o = ((Reference)o).get();
  204. if (o != null) {
  205. return (JavaClass)o;
  206. } else {
  207. missLocalEvicted++;
  208. }
  209. }
  210. return null;
  211. }
  212. /**
  213. * Find an already defined JavaClass in the shared cache.
  214. */
  215. private JavaClass findClassShared(URL url) {
  216. return (JavaClass)sharedCache.get(url);
  217. }
  218. private URL toURL(String className) {
  219. URL url = (URL)nameMap.get(className);
  220. if (url==null) {
  221. String classFile = className.replace('.', '/');
  222. url = loader.getResource( classFile + ".class" );
  223. nameMap.put(className, url);
  224. }
  225. return url;
  226. }
  227. /**
  228. * Lookup a JavaClass object from the Class Name provided.
  229. */
  230. public JavaClass loadClass( String className ) throws ClassNotFoundException {
  231. // translate to a URL
  232. long time = System.currentTimeMillis();
  233. java.net.URL url = toURL(className);
  234. timeManipulatingURLs += (System.currentTimeMillis() - time);
  235. if (url==null) throw new ClassNotFoundException(className + " not found.");
  236. JavaClass clazz = null;
  237. // Look in the appropriate cache
  238. if (useSharedCache) {
  239. clazz = findClassShared(url);
  240. if (clazz != null) { cacheHitsShared++; return clazz; }
  241. } else {
  242. clazz = findClassLocal(url);
  243. if (clazz != null) { cacheHitsLocal++; return clazz; }
  244. }
  245. // Didn't find it in either cache
  246. misses++;
  247. try {
  248. // Load it
  249. String classFile = className.replace('.', '/');
  250. InputStream is = (useSharedCache?url.openStream():loader.getResourceAsStream( classFile + ".class" ));
  251. if (is == null) {
  252. throw new ClassNotFoundException(className + " not found.");
  253. }
  254. ClassParser parser = new ClassParser( is, className );
  255. clazz = parser.parse();
  256. // Cache it
  257. storeClassAsReference(url, clazz );
  258. timeSpentLoading += (System.currentTimeMillis() - time);
  259. classesLoadedCount++;
  260. return clazz;
  261. } catch (IOException e) {
  262. throw new ClassNotFoundException( e.toString() );
  263. }
  264. }
  265. /**
  266. * Produce a report on cache usage.
  267. */
  268. public String report() {
  269. StringBuffer sb = new StringBuffer();
  270. sb.append("BCEL repository report.");
  271. if (useSharedCache) sb.append(" (shared cache)");
  272. else sb.append(" (local cache)");
  273. sb.append(" Total time spent loading: "+timeSpentLoading+"ms.");
  274. sb.append(" Time spent manipulating URLs: "+timeManipulatingURLs+"ms.");
  275. sb.append(" Classes loaded: "+classesLoadedCount+".");
  276. if (useSharedCache) {
  277. sb.append(" Shared cache size: "+sharedCache.size());
  278. sb.append(" Shared cache (hits/missDueToEviction): ("+cacheHitsShared+"/"+missSharedEvicted+").");
  279. } else {
  280. sb.append(" Local cache size: "+localCache.size());
  281. sb.append(" Local cache (hits/missDueToEviction): ("+cacheHitsLocal+"/"+missLocalEvicted+").");
  282. }
  283. return sb.toString();
  284. }
  285. /**
  286. * Returns an array of the stats, for testing, the order is fixed:
  287. * 0=time spent loading (static)
  288. * 1=time spent manipulating URLs (static)
  289. * 2=classes loaded (static)
  290. * 3=cache hits shared (static)
  291. * 4=misses in shared due to eviction (static)
  292. * 5=cache hits local
  293. * 6=misses in local due to eviction
  294. * 7=shared cache size
  295. */
  296. public long[] reportStats() {
  297. return new long[]{timeSpentLoading,timeManipulatingURLs,classesLoadedCount,
  298. cacheHitsShared,missSharedEvicted,cacheHitsLocal,missLocalEvicted,
  299. sharedCache.size()};
  300. }
  301. /**
  302. * Reset statistics and clear all caches
  303. */
  304. public void reset() {
  305. timeManipulatingURLs = 0L;
  306. timeSpentLoading = 0L;
  307. classesLoadedCount = 0;
  308. cacheHitsLocal = 0;
  309. cacheHitsShared = 0;
  310. missSharedEvicted = 0;
  311. missLocalEvicted = 0;
  312. misses = 0;
  313. clear();
  314. }
  315. public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
  316. return loadClass(clazz.getName());
  317. }
  318. /** Clear all entries from the local cache */
  319. public void clear() {
  320. if (useSharedCache) sharedCache.clear();
  321. else localCache.clear();
  322. }
  323. }