Skip to content

Commit

Permalink
Avoid attempted duplicate class definition in TestClassLoader
Browse files Browse the repository at this point in the history
  • Loading branch information
sbrannen committed May 7, 2023
1 parent 1c9c018 commit 4b45db0
Showing 1 changed file with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;

import org.junit.platform.commons.util.ClassLoaderUtils;
Expand All @@ -34,6 +36,8 @@ public class TestClassLoader extends URLClassLoader {

private static final Predicate<Class<?>> notTestClassLoader = clazz -> !clazz.equals(TestClassLoader.class);

private final Map<String, Class<?>> cachedClasses = new ConcurrentHashMap<>();

private final Predicate<String> classNameFilter;

/**
Expand Down Expand Up @@ -64,7 +68,19 @@ public TestClassLoader(Predicate<String> classNameFilter) {

@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return (this.classNameFilter.test(name) ? findClass(name) : super.loadClass(name));
Class<?> clazz = this.cachedClasses.get(name);
if (clazz != null) {
return clazz;
}
synchronized (this.cachedClasses) {
clazz = this.cachedClasses.get(name);
if (clazz != null) {
return clazz;
}
clazz = this.classNameFilter.test(name) ? findClass(name) : super.loadClass(name);
this.cachedClasses.put(name, clazz);
return clazz;
}
}

/**
Expand Down

0 comments on commit 4b45db0

Please sign in to comment.