3434import com .sun .source .util .TreeScanner ;
3535import com .sun .source .util .Trees ;
3636import com .sun .tools .javac .api .JavacTool ;
37+ import com .sun .tools .javac .util .Context ;
3738import java .io .IOException ;
3839import java .util .List ;
3940import java .util .Locale ;
@@ -56,6 +57,7 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
5657 InMemoryJavaFileManager fileManager =
5758 new InMemoryJavaFileManager (
5859 compiler .getStandardFileManager (diagnosticCollector , Locale .getDefault (), UTF_8 ));
60+ Context context = new Context ();
5961 JavacTask task =
6062 ((JavacTool ) compiler )
6163 .getTask (
@@ -64,7 +66,8 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
6466 diagnosticCollector ,
6567 ImmutableSet .<String >of (),
6668 ImmutableSet .<String >of (),
67- sources );
69+ sources ,
70+ context );
6871 try {
6972 Iterable <? extends CompilationUnitTree > parsedCompilationUnits = task .parse ();
7073 List <Diagnostic <? extends JavaFileObject >> diagnostics = diagnosticCollector .getDiagnostics ();
@@ -76,6 +79,8 @@ static ParseResult parse(Iterable<? extends JavaFileObject> sources) {
7679 sortDiagnosticsByKind (diagnostics ), parsedCompilationUnits , Trees .instance (task ));
7780 } catch (IOException e ) {
7881 throw new RuntimeException (e );
82+ } finally {
83+ DummyJavaCompilerSubclass .closeCompiler (context );
7984 }
8085 }
8186
@@ -175,4 +180,19 @@ Trees trees() {
175180 return trees ;
176181 }
177182 }
183+
184+ // JavaCompiler.compilerKey has protected access until Java 9, so this is a workaround.
185+ private static final class DummyJavaCompilerSubclass extends com .sun .tools .javac .main .JavaCompiler {
186+ private static void closeCompiler (Context context ) {
187+ com .sun .tools .javac .main .JavaCompiler compiler = context .get (compilerKey );
188+ if (compiler != null ) {
189+ compiler .close ();
190+ }
191+ }
192+
193+ private DummyJavaCompilerSubclass () {
194+ // not instantiable
195+ super (null );
196+ }
197+ }
178198}
0 commit comments