Skip to content

Commit

Permalink
fix: Synchronize access to anonymous type cache
Browse files Browse the repository at this point in the history
  • Loading branch information
I-Al-Istannen committed Aug 28, 2023
1 parent dae341a commit bd828bd
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/main/java/spoon/reflect/factory/TypeFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ public boolean matches(CtClass<T> element) {
// If the class name is an integer, the class is an anonymous class, otherwise,
// it is a standard class.
//TODO reset cache when type is modified
return getFromCache(t, className, k -> {
return getAnonymousTypeFromCache(t, className, k -> {
//the searching for declaration of anonymous class is expensive
//do that only once and store it in cache of CtType
final List<CtNewClass> anonymousClasses = t.getElements(new TypeFilter<CtNewClass>(CtNewClass.class) {
Expand All @@ -488,15 +488,19 @@ public boolean matches(CtNewClass element) {
return null;
}

private static final String CACHE_KEY = TypeFactory.class.getName() + "-AnnonymousTypeCache";
private static final String ANONYMOUS_TYPES_CACHE_KEY = TypeFactory.class.getName() + "-AnnonymousTypeCache";

private <T, K> T getFromCache(CtElement element, K key, Function<K, T> valueResolver) {
Map<K, T> cache = (Map<K, T>) element.getMetadata(CACHE_KEY);
if (cache == null) {
cache = new HashMap<>();
element.putMetadata(CACHE_KEY, cache);
private <T, K> T getAnonymousTypeFromCache(CtElement element, K key, Function<K, T> valueResolver) {
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (element) {
@SuppressWarnings("unchecked")
Map<K, T> cache = (Map<K, T>) element.getMetadata(ANONYMOUS_TYPES_CACHE_KEY);
if (cache == null) {
cache = new HashMap<>();
element.putMetadata(ANONYMOUS_TYPES_CACHE_KEY, cache);
}
return cache.computeIfAbsent(key, valueResolver);
}
return cache.computeIfAbsent(key, valueResolver);
}

private boolean isNumber(String str) {
Expand Down

0 comments on commit bd828bd

Please sign in to comment.