Skip to content

Commit

Permalink
Prevent some classes to be GCed
Browse files Browse the repository at this point in the history
  • Loading branch information
cstamas committed Feb 7, 2025
1 parent 4f21915 commit 37eae3e
Showing 1 changed file with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -71,20 +72,23 @@ protected static final class Context {
private final Set<String> originalClassRealmIds;
private final ClassLoader tccl;
private final Function<ExecutorRequest, Integer> exec;
private final Collection<Object> keepAlive;

private Context(
URLClassLoader bootClassLoader,
String version,
Object classWorld,
Set<String> originalClassRealmIds,
ClassLoader tccl,
Function<ExecutorRequest, Integer> exec) {
Function<ExecutorRequest, Integer> exec,
Collection<Object> keepAlive) {
this.bootClassLoader = bootClassLoader;
this.version = version;
this.classWorld = classWorld;
this.originalClassRealmIds = originalClassRealmIds;
this.tccl = tccl;
this.exec = exec;
this.keepAlive = keepAlive;
}
}

Expand Down Expand Up @@ -262,13 +266,15 @@ protected Context doCreate(Path mavenHome, ExecutorRequest executorRequest) {
(Class<?>) launcherClass.getMethod("getMainClass").invoke(launcher);
String version = getMavenVersion(cliClass);
Function<ExecutorRequest, Integer> exec;
ArrayList<Object> keepAlive = new ArrayList<>();

if (version.startsWith("3.")) {
// 3.x
if (!ExecutorRequest.MVN.equals(executorRequest.command())) {
throw new IllegalArgumentException(getClass().getSimpleName() + "w/ mvn3 does not support command "
+ executorRequest.command());
}
keepAlive.add(cliClass.getClassLoader().loadClass("org.fusesource.jansi.internal.JansiLoader"));
Constructor<?> newMavenCli = cliClass.getConstructor(classWorld.getClass());
Object mavenCli = newMavenCli.newInstance(classWorld);
Class<?>[] parameterTypes = {String[].class, String.class, PrintStream.class, PrintStream.class};
Expand All @@ -293,6 +299,7 @@ protected Context doCreate(Path mavenHome, ExecutorRequest executorRequest) {
};
} else {
// assume 4.x
keepAlive.add(cliClass.getClassLoader().loadClass("org.jline.nativ.JLineNativeLoader"));
Method mainMethod = cliClass.getMethod(
"main",
String[].class,
Expand All @@ -319,7 +326,13 @@ protected Context doCreate(Path mavenHome, ExecutorRequest executorRequest) {
}

return new Context(
bootClassLoader, version, classWorld, originalClassRealmIds, cliClass.getClassLoader(), exec);
bootClassLoader,
version,
classWorld,
originalClassRealmIds,
cliClass.getClassLoader(),
exec,
keepAlive);
} catch (Exception e) {
throw new ExecutorException("Failed to create executor", e);
} finally {
Expand Down

0 comments on commit 37eae3e

Please sign in to comment.