Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Synchronize access to anonymous type cache #5403

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading