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.

WeavedClassCache.java 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*******************************************************************************
  2. * Copyright (c) 2012 Contributors.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * John Kew (vmware) initial implementation
  11. * Lyor Goldstein (vmware) add support for weaved class being re-defined
  12. *******************************************************************************/
  13. package org.aspectj.weaver.tools.cache;
  14. import java.util.LinkedList;
  15. import java.util.List;
  16. import org.aspectj.bridge.IMessage;
  17. import org.aspectj.bridge.IMessageHandler;
  18. import org.aspectj.bridge.Message;
  19. import org.aspectj.bridge.MessageUtil;
  20. import org.aspectj.weaver.tools.GeneratedClassHandler;
  21. /**
  22. * Manages a cache of weaved and generated classes similar to Eclipse Equinox,
  23. * except designed to operate across multiple restarts of the JVM and with one
  24. * cache per classloader; allowing URLClassLoaders with the same set of URI
  25. * paths to share the same cache (with the default configuration).
  26. * <p/>
  27. * To enable the default configuration two system properties must be set:
  28. * <pre>
  29. * "-Daj.weaving.cache.enabled=true"
  30. * "-Daj.weaving.cache.dir=/some/directory"
  31. * </pre>
  32. * <p/>
  33. * The class cache is often something that application developers or
  34. * containers would like to manage, so there are a few interfaces for overriding the
  35. * default behavior and performing other management functions.
  36. * <p/>
  37. * {@link CacheBacking} <br/>
  38. * Provides an interface for implementing a custom backing store
  39. * for the cache; The default implementation in {@link DefaultFileCacheBacking}
  40. * provides a naive file-backed cache. An alternate implementation may ignore
  41. * caching until signaled explicitly by the application, or only cache files
  42. * for a specific duration. This class delegates the locking and synchronization
  43. * requirements to the CacheBacking implementation.
  44. * <p/>
  45. * {@link CacheKeyResolver} <br/>
  46. * Provides methods for creating keys from classes to be cached and for
  47. * creating the "scope" of the cache itself for a given classloader and aspect
  48. * list. The default implementation is provided by {@link DefaultCacheKeyResolver}
  49. * but an alternate implementation may want to associate a cache with a particular
  50. * application running underneath a container.
  51. * <p/>
  52. * This naive cache does not normally invalidate *any* classes; the interfaces above
  53. * must be used to implement more intelligent behavior. Cache invalidation
  54. * problems may occur in at least three scenarios:
  55. * <pre>
  56. * 1. New aspects are added dynamically somewhere in the classloader hierarchy; affecting
  57. * other classes elsewhere.
  58. * 2. Use of declare parent in aspects to change the type hierarchy; if the cache
  59. * has not invalidated the right classes in the type hierarchy aspectj may not
  60. * be reconstruct the class incorrectly.
  61. * 3. Similarly to (2), the addition of fields or methods on classes which have
  62. * already been weaved and cached could have inter-type conflicts.
  63. * </pre>
  64. */
  65. public class WeavedClassCache {
  66. public static final String WEAVED_CLASS_CACHE_ENABLED = "aj.weaving.cache.enabled";
  67. public static final String CACHE_IMPL = SimpleCacheFactory.CACHE_IMPL;
  68. private static CacheFactory DEFAULT_FACTORY = new DefaultCacheFactory();
  69. public static final byte[] ZERO_BYTES = new byte[0];
  70. private final IMessageHandler messageHandler;
  71. private final GeneratedCachedClassHandler cachingClassHandler;
  72. private final CacheBacking backing;
  73. private final CacheStatistics stats;
  74. private final CacheKeyResolver resolver;
  75. private final String name;
  76. private static final List<WeavedClassCache> cacheRegistry = new LinkedList<WeavedClassCache>();
  77. protected WeavedClassCache(GeneratedClassHandler existingClassHandler,
  78. IMessageHandler messageHandler,
  79. String name,
  80. CacheBacking backing,
  81. CacheKeyResolver resolver) {
  82. this.resolver = resolver;
  83. this.name = name;
  84. this.backing = backing;
  85. this.messageHandler = messageHandler;
  86. // wrap the existing class handler with a caching version
  87. cachingClassHandler = new GeneratedCachedClassHandler(this, existingClassHandler);
  88. this.stats = new CacheStatistics();
  89. synchronized (cacheRegistry) {
  90. cacheRegistry.add(this);
  91. }
  92. }
  93. /**
  94. * Creates a new cache using the resolver and backing returned by the DefaultCacheFactory.
  95. *
  96. * @param loader classloader for this cache
  97. * @param aspects list of aspects used by the WeavingAdapter
  98. * @param existingClassHandler the existing GeneratedClassHandler used by the weaver
  99. * @param messageHandler the existing messageHandler used by the weaver
  100. * @return
  101. */
  102. public static WeavedClassCache createCache(ClassLoader loader, List<String> aspects, GeneratedClassHandler existingClassHandler, IMessageHandler messageHandler) {
  103. CacheKeyResolver resolver = DEFAULT_FACTORY.createResolver();
  104. String name = resolver.createClassLoaderScope(loader, aspects);
  105. if (name == null) {
  106. return null;
  107. }
  108. CacheBacking backing = DEFAULT_FACTORY.createBacking(name);
  109. if (backing != null) {
  110. return new WeavedClassCache(existingClassHandler, messageHandler, name, backing, resolver);
  111. }
  112. return null;
  113. }
  114. public String getName() {
  115. return name;
  116. }
  117. /**
  118. * The Cache and be extended in two ways, through a specialized CacheKeyResolver and
  119. * a specialized CacheBacking. The default factory used to create these classes can
  120. * be set with this method. Since each weaver will create a cache, this method must be
  121. * called before the weaver is first initialized.
  122. *
  123. * @param factory
  124. */
  125. public static void setDefaultCacheFactory(CacheFactory factory) {
  126. DEFAULT_FACTORY = factory;
  127. }
  128. /**
  129. * Created a key for a generated class
  130. *
  131. * @param className ClassName, e.g. "com.foo.Bar"
  132. * @return the cache key, or null if no caching should be performed
  133. */
  134. public CachedClassReference createGeneratedCacheKey(String className) {
  135. return resolver.generatedKey(className);
  136. }
  137. /**
  138. * Create a key for a normal weaved class
  139. *
  140. * @param className ClassName, e.g. "com.foo.Bar"
  141. * @param originalBytes Original byte array of the class
  142. * @return a cache key, or null if no caching should be performed
  143. */
  144. public CachedClassReference createCacheKey(String className, byte[] originalBytes) {
  145. return resolver.weavedKey(className, originalBytes);
  146. }
  147. /**
  148. * Returns a generated class handler which wraps the handler this cache was initialized
  149. * with; this handler should be used to make sure that generated classes are added
  150. * to the cache
  151. */
  152. public GeneratedClassHandler getCachingClassHandler() {
  153. return cachingClassHandler;
  154. }
  155. /**
  156. * Has caching been enabled through the System property,
  157. * WEAVED_CLASS_CACHE_ENABLED
  158. *
  159. * @return true if caching is enabled
  160. */
  161. public static boolean isEnabled() {
  162. String enabled = System.getProperty(WEAVED_CLASS_CACHE_ENABLED);
  163. String impl = System.getProperty(CACHE_IMPL);
  164. return (enabled != null && (impl == null || !SimpleCache.IMPL_NAME.equalsIgnoreCase(impl) ) );
  165. }
  166. /**
  167. * Put a class in the cache
  168. *
  169. * @param ref reference to the entry, as created through createCacheKey
  170. * @param classBytes pre-weaving class bytes
  171. * @param weavedBytes bytes to cache
  172. */
  173. public void put(CachedClassReference ref, byte[] classBytes, byte[] weavedBytes) {
  174. CachedClassEntry.EntryType type = CachedClassEntry.EntryType.WEAVED;
  175. if (ref.getKey().matches(resolver.getGeneratedRegex())) {
  176. type = CachedClassEntry.EntryType.GENERATED;
  177. }
  178. backing.put(new CachedClassEntry(ref, weavedBytes, type), classBytes);
  179. stats.put();
  180. }
  181. /**
  182. * Get a cache value
  183. *
  184. * @param ref reference to the cache entry, created through createCacheKey
  185. * @param classBytes Pre-weaving class bytes - required to ensure that
  186. * cached aspects refer to an unchanged original class
  187. * @return the CacheEntry, or null if no entry exists in the cache
  188. */
  189. public CachedClassEntry get(CachedClassReference ref, byte[] classBytes) {
  190. CachedClassEntry entry = backing.get(ref, classBytes);
  191. if (entry == null) {
  192. stats.miss();
  193. } else {
  194. stats.hit();
  195. if (entry.isGenerated()) stats.generated();
  196. if (entry.isWeaved()) stats.weaved();
  197. if (entry.isIgnored()) stats.ignored();
  198. }
  199. return entry;
  200. }
  201. /**
  202. * Put a cache entry to indicate that the class should not be
  203. * weaved; the original bytes of the class should be used.
  204. *
  205. * @param ref The cache reference
  206. * @param classBytes The un-weaved class bytes
  207. */
  208. public void ignore(CachedClassReference ref, byte[] classBytes) {
  209. stats.putIgnored();
  210. backing.put(new CachedClassEntry(ref, ZERO_BYTES, CachedClassEntry.EntryType.IGNORED), classBytes);
  211. }
  212. /**
  213. * Invalidate a cache entry
  214. *
  215. * @param ref
  216. */
  217. public void remove(CachedClassReference ref) {
  218. backing.remove(ref);
  219. }
  220. /**
  221. * Clear the entire cache
  222. */
  223. public void clear() {
  224. backing.clear();
  225. }
  226. /**
  227. * Get the statistics associated with this cache, or
  228. * null if statistics have not been enabled.
  229. *
  230. * @return
  231. */
  232. public CacheStatistics getStats() {
  233. return stats;
  234. }
  235. /**
  236. * Return a list of all WeavedClassCaches which have been initialized
  237. *
  238. * @return
  239. */
  240. public static List<WeavedClassCache> getCaches() {
  241. synchronized (cacheRegistry) {
  242. return new LinkedList<WeavedClassCache>(cacheRegistry);
  243. }
  244. }
  245. protected void error(String message, Throwable th) {
  246. messageHandler.handleMessage(new Message(message, IMessage.ERROR, th, null));
  247. }
  248. protected void error(String message) {
  249. MessageUtil.error(messageHandler, message);
  250. }
  251. protected void info(String message) {
  252. MessageUtil.info(message);
  253. }
  254. }