Skip to content

Commit

Permalink
Close JavaCompiler objects to avoid resource leaks
Browse files Browse the repository at this point in the history
RELNOTES=Close JavaCompiler objects to avoid resource leaks
PiperOrigin-RevId: 340553115
  • Loading branch information
java-team-github-bot authored and Compile-Testing Team committed Nov 4, 2020
1 parent 2a47a53 commit cd2c0a8
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/main/java/com/google/testing/compile/Parser.java
Expand Up @@ -34,6 +34,7 @@
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.util.Context;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
Expand All @@ -56,6 +57,7 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
InMemoryJavaFileManager fileManager =
new InMemoryJavaFileManager(
compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8));
Context context = new Context();
JavacTask task =
((JavacTool) compiler)
.getTask(
Expand All @@ -64,7 +66,8 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
diagnosticCollector,
ImmutableSet.<String>of(),
ImmutableSet.<String>of(),
sources);
sources,
context);
try {
Iterable<? extends CompilationUnitTree> parsedCompilationUnits = task.parse();
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
Expand All @@ -76,6 +79,8 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
sortDiagnosticsByKind(diagnostics), parsedCompilationUnits, Trees.instance(task));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
DummyJavaCompilerSubclass.closeCompiler(context);
}
}

Expand Down Expand Up @@ -175,4 +180,19 @@ Trees trees() {
return trees;
}
}

// JavaCompiler.compilerKey has protected access until Java 9, so this is a workaround.
private static final class DummyJavaCompilerSubclass extends com.sun.tools.javac.main.JavaCompiler {
private static void closeCompiler(Context context) {
com.sun.tools.javac.main.JavaCompiler compiler = context.get(compilerKey);
if (compiler != null) {
compiler.close();
}
}

private DummyJavaCompilerSubclass() {
// not instantiable
super(null);
}
}
}

0 comments on commit cd2c0a8

Please sign in to comment.