8157391: jdeps left JarFile open
authormchung
Fri, 20 May 2016 09:47:00 -0700
changeset 38530 8e89d567748c
parent 38529 58cf7e51c16d
child 38531 c449daa25b45
8157391: jdeps left JarFile open Reviewed-by: alanb
langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Archive.java
langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ClassFileReader.java
langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java
langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java
langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleInfoBuilder.java
langtools/test/tools/jdeps/lib/JdepsUtil.java
langtools/test/tools/jdeps/modules/CheckModuleTest.java
langtools/test/tools/jdeps/modules/GenModuleInfo.java
langtools/test/tools/jdeps/modules/InverseDeps.java
langtools/test/tools/jdeps/modules/ModuleTest.java
langtools/test/tools/jdeps/modules/SplitPackage.java
langtools/test/tools/jdeps/modules/TransitiveDeps.java
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Archive.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Archive.java	Fri May 20 09:47:00 2016 -0700
@@ -27,6 +27,7 @@
 
 import com.sun.tools.classfile.Dependency.Location;
 
+import java.io.Closeable;
 import java.io.IOException;
 import java.io.UncheckedIOException;
 import java.net.URI;
@@ -43,7 +44,7 @@
 /**
  * Represents the source of the class files.
  */
-public class Archive {
+public class Archive implements Closeable {
     public static Archive getInstance(Path p) {
         try {
             return new Archive(p, ClassFileReader.newInstance(p));
@@ -178,6 +179,13 @@
     private boolean isJrt() {
         return location != null && location.getScheme().equals("jrt");
     }
+
+    @Override
+    public void close() throws IOException {
+        if (reader != null)
+            reader.close();
+    }
+
     interface Visitor {
         void visit(Location origin, Location target);
     }
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ClassFileReader.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ClassFileReader.java	Fri May 20 09:47:00 2016 -0700
@@ -29,6 +29,7 @@
 import com.sun.tools.classfile.ConstantPoolException;
 import com.sun.tools.classfile.Dependencies.ClassFileError;
 
+import java.io.Closeable;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
@@ -54,7 +55,7 @@
  * ClassFileReader reads ClassFile(s) of a given path that can be
  * a .class file, a directory, or a JAR file.
  */
-public class ClassFileReader {
+public class ClassFileReader implements Closeable {
     /**
      * Returns a ClassFileReader instance of a given path.
      */
@@ -177,6 +178,10 @@
         return fn.endsWith(".class");
     }
 
+    @Override
+    public void close() throws IOException {
+    }
+
     class FileIterator implements Iterator<ClassFile> {
         int count;
         FileIterator() {
@@ -306,6 +311,11 @@
             this.jarfile = jf;
         }
 
+        @Override
+        public void close() throws IOException {
+            jarfile.close();
+        }
+
         protected Set<String> scan() {
             try (JarFile jf = new JarFile(path.toFile())) {
                 return jf.stream().map(JarEntry::getName)
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Fri May 20 09:47:00 2016 -0700
@@ -64,7 +64,7 @@
 import java.util.function.Supplier;
 import java.util.stream.Stream;
 
-public class JdepsConfiguration {
+public class JdepsConfiguration implements AutoCloseable {
     // the token for "all modules on the module path"
     public static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
     public static final String ALL_DEFAULT = "ALL-DEFAULT";
@@ -304,6 +304,19 @@
         }
     }
 
+    /*
+     * Close all archives e.g. JarFile
+     */
+    @Override
+    public void close() throws IOException {
+        for (Archive archive : initialArchives)
+            archive.close();
+        for (Archive archive : classpathArchives)
+            archive.close();
+        for (Module module : nameToModule.values())
+            module.close();
+    }
+
     static class SystemModuleFinder implements ModuleFinder {
         private static final String JAVA_HOME = System.getProperty("java.home");
         private static final String JAVA_SE = "java.se";
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java	Fri May 20 09:47:00 2016 -0700
@@ -499,40 +499,41 @@
     }
 
     boolean run() throws IOException {
-        JdepsConfiguration config = buildConfig();
+        try (JdepsConfiguration config = buildConfig()) {
 
-        // detect split packages
-        config.splitPackages().entrySet().stream()
-            .sorted(Map.Entry.comparingByKey())
-            .forEach(e -> System.out.format("split package: %s %s%n", e.getKey(),
-                                            e.getValue().toString()));
+            // detect split packages
+            config.splitPackages().entrySet().stream()
+                .sorted(Map.Entry.comparingByKey())
+                .forEach(e -> System.out.format("split package: %s %s%n", e.getKey(),
+                    e.getValue().toString()));
 
-        // check if any module specified in -requires is missing
-        Stream.concat(options.addmods.stream(), options.requires.stream())
-              .filter(mn -> !config.isValidToken(mn))
-              .forEach(mn -> config.findModule(mn).orElseThrow(() ->
-                  new UncheckedBadArgs(new BadArgs("err.module.not.found", mn))));
+            // check if any module specified in -requires is missing
+            Stream.concat(options.addmods.stream(), options.requires.stream())
+                .filter(mn -> !config.isValidToken(mn))
+                .forEach(mn -> config.findModule(mn).orElseThrow(() ->
+                    new UncheckedBadArgs(new BadArgs("err.module.not.found", mn))));
 
-        // -genmoduleinfo
-        if (options.genModuleInfo != null) {
-            return genModuleInfo(config);
-        }
+            // -genmoduleinfo
+            if (options.genModuleInfo != null) {
+                return genModuleInfo(config);
+            }
 
-        // -check
-        if (options.checkModuleDeps != null) {
-            return new ModuleAnalyzer(config, log, options.checkModuleDeps).run();
-        }
+            // -check
+            if (options.checkModuleDeps != null) {
+                return new ModuleAnalyzer(config, log, options.checkModuleDeps).run();
+            }
 
-        if (options.dotOutputDir != null &&
+            if (options.dotOutputDir != null &&
                 (options.verbose == SUMMARY || options.verbose == MODULE) &&
                 !options.addmods.isEmpty() && inputArgs.isEmpty()) {
-            return new ModuleAnalyzer(config, log).genDotFiles(options.dotOutputDir);
-        }
+                return new ModuleAnalyzer(config, log).genDotFiles(options.dotOutputDir);
+            }
 
-        if (options.inverse) {
-            return analyzeInverseDeps(config);
-        } else {
-            return analyzeDeps(config);
+            if (options.inverse) {
+                return analyzeInverseDeps(config);
+            } else {
+                return analyzeDeps(config);
+            }
         }
     }
 
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleInfoBuilder.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleInfoBuilder.java	Fri May 20 09:47:00 2016 -0700
@@ -119,6 +119,11 @@
             // generate module-info.java
             descriptors().forEach(md -> writeModuleInfo(outputdir, md));
 
+            // done parsing
+            for (Module m : automaticModules()) {
+                m.close();
+            }
+
             // find any missing dependences
             return automaticModules().stream()
                         .flatMap(analyzer::requires)
--- a/langtools/test/tools/jdeps/lib/JdepsUtil.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/lib/JdepsUtil.java	Fri May 20 09:47:00 2016 -0700
@@ -29,6 +29,7 @@
 import com.sun.tools.jdeps.JdepsWriter;
 import com.sun.tools.jdeps.ModuleAnalyzer;
 
+import java.io.Closeable;
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintStream;
@@ -73,7 +74,7 @@
         return new Command(cmd);
     }
 
-    public static class Command {
+    public static class Command implements Closeable {
 
         final StringWriter sw = new StringWriter();
         final PrintWriter pw = new PrintWriter(sw);
@@ -81,6 +82,7 @@
         final JdepsConfiguration.Builder builder =  new JdepsConfiguration.Builder();
         final Set<String> requires = new HashSet<>();
 
+        JdepsConfiguration configuration;
         Analyzer.Type verbose = Analyzer.Type.PACKAGE;
         boolean apiOnly = false;
 
@@ -176,12 +178,14 @@
         }
 
         public JdepsConfiguration configuration() throws IOException {
-            JdepsConfiguration config = builder.build();
-            requires.forEach(name -> {
-                ModuleDescriptor md = config.findModuleDescriptor(name).get();
-                filter.requires(name, md.packages());
-            });
-            return config;
+            if (configuration == null) {
+                this.configuration = builder.build();
+                requires.forEach(name -> {
+                    ModuleDescriptor md = configuration.findModuleDescriptor(name).get();
+                    filter.requires(name, md.packages());
+                });
+            }
+            return configuration;
         }
 
         private JdepsWriter writer() {
@@ -208,6 +212,11 @@
         public void dumpOutput(PrintStream out) {
             out.println(sw.toString());
         }
+
+        @Override
+        public void close() throws IOException {
+            configuration.close();
+        }
     }
 
     /**
--- a/langtools/test/tools/jdeps/modules/CheckModuleTest.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/CheckModuleTest.java	Fri May 20 09:47:00 2016 -0700
@@ -78,19 +78,19 @@
 
     @Test(dataProvider = "javaBase")
     public void testJavaBase(String name, ModuleMetaData data) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -check %s -mp %s%n", name, MODS_DIR)
-        );
-        jdeps.appModulePath(MODS_DIR.toString());
+        String cmd = String.format("jdeps -check %s -mp %s%n", name, MODS_DIR);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.appModulePath(MODS_DIR.toString());
 
-        ModuleAnalyzer analyzer = jdeps.getModuleAnalyzer(Set.of(name));
-        assertTrue(analyzer.run());
-        jdeps.dumpOutput(System.err);
+            ModuleAnalyzer analyzer = jdeps.getModuleAnalyzer(Set.of(name));
+            assertTrue(analyzer.run());
+            jdeps.dumpOutput(System.err);
 
-        ModuleDescriptor[] descriptors = analyzer.descriptors(name);
-        for (int i=0; i < 3; i++) {
-            descriptors[i].requires().stream()
-                .forEach(req -> data.checkRequires(req));
+            ModuleDescriptor[] descriptors = analyzer.descriptors(name);
+            for (int i = 0; i < 3; i++) {
+                descriptors[i].requires().stream()
+                    .forEach(req -> data.checkRequires(req));
+            }
         }
     }
 
@@ -137,26 +137,27 @@
 
     @Test(dataProvider = "modules")
     public void modularTest(String name, ModuleMetaData[] data) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -check %s -mp %s%n", name, MODS_DIR)
-        );
-        jdeps.appModulePath(MODS_DIR.toString());
+        String cmd = String.format("jdeps -check %s -mp %s%n", name, MODS_DIR);
 
-        ModuleAnalyzer analyzer = jdeps.getModuleAnalyzer(Set.of(name));
-        assertTrue(analyzer.run());
-        jdeps.dumpOutput(System.err);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.appModulePath(MODS_DIR.toString());
+
+            ModuleAnalyzer analyzer = jdeps.getModuleAnalyzer(Set.of(name));
+            assertTrue(analyzer.run());
+            jdeps.dumpOutput(System.err);
 
-        // compare the module descriptors and the suggested versions
-        ModuleDescriptor[] descriptors = analyzer.descriptors(name);
-        for (int i=0; i < 3; i++) {
-            ModuleMetaData metaData = data[i];
-            descriptors[i].requires().stream()
-                .forEach(req -> metaData.checkRequires(req));
+            // compare the module descriptors and the suggested versions
+            ModuleDescriptor[] descriptors = analyzer.descriptors(name);
+            for (int i = 0; i < 3; i++) {
+                ModuleMetaData metaData = data[i];
+                descriptors[i].requires().stream()
+                    .forEach(req -> metaData.checkRequires(req));
+            }
+
+            Map<String, Set<String>> unused = analyzer.unusedQualifiedExports(name);
+            // verify unuused qualified exports
+            assertEquals(unused, data[0].exports);
         }
-
-        Map<String, Set<String>> unused = analyzer.unusedQualifiedExports(name);
-        // verify unuused qualified exports
-        assertEquals(unused, data[0].exports);
     }
 
 }
--- a/langtools/test/tools/jdeps/modules/GenModuleInfo.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/GenModuleInfo.java	Fri May 20 09:47:00 2016 -0700
@@ -107,8 +107,7 @@
                 .map(Path::toString);
 
         JdepsUtil.jdeps(Stream.concat(Stream.of("-genmoduleinfo", DEST_DIR.toString()),
-                            files)
-                    .toArray(String[]::new));
+                                      files).toArray(String[]::new));
 
         // check file exists
         Arrays.stream(modules)
@@ -162,14 +161,13 @@
     }
 
     private Set<String> packages(Path dir) {
-        try {
-            return Files.find(dir, Integer.MAX_VALUE,
+        try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
                              ((path, attrs) -> attrs.isRegularFile() &&
-                                               path.toString().endsWith(".class")))
-                        .map(path -> toPackageName(dir.relativize(path)))
-                        .filter(pkg -> pkg.length() > 0)   // module-info
-                        .distinct()
-                        .collect(Collectors.toSet());
+                                               path.toString().endsWith(".class")))) {
+            return stream.map(path -> toPackageName(dir.relativize(path)))
+                         .filter(pkg -> pkg.length() > 0)   // module-info
+                         .distinct()
+                         .collect(Collectors.toSet());
         } catch (IOException x) {
             throw new UncheckedIOException(x);
         }
--- a/langtools/test/tools/jdeps/modules/InverseDeps.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/InverseDeps.java	Fri May 20 09:47:00 2016 -0700
@@ -117,26 +117,28 @@
 
     @Test(dataProvider = "testrequires")
     public void testrequires(String name, String[][] expected) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -modulepath %s -requires %s -addmods %s%n",
-                MODS_DIR, name, modules.stream().collect(Collectors.joining(","))
-        ));
-        jdeps.appModulePath(MODS_DIR.toString())
-             .addmods(modules)
-             .requires(Set.of(name));
+        String cmd1 = String.format("jdeps -inverse -modulepath %s -requires %s -addmods %s%n",
+                MODS_DIR, name, modules.stream().collect(Collectors.joining(",")));
 
-        runJdeps(jdeps, expected);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd1)) {
+            jdeps.appModulePath(MODS_DIR.toString())
+                .addmods(modules)
+                .requires(Set.of(name));
+
+            runJdeps(jdeps, expected);
+        }
 
-        // automatic module
-        jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -modulepath %s -requires %s -addmods ALL-MODULE-PATH%n",
-                          LIBS_DIR, name)
-        );
-        jdeps.appModulePath(MODS_DIR.toString())
-            .addmods(Set.of("ALL-MODULE-PATH"))
-            .requires(Set.of(name));
+        String cmd2 = String.format("jdeps -inverse -modulepath %s -requires %s" +
+            " -addmods ALL-MODULE-PATH%n", LIBS_DIR, name);
 
-        runJdeps(jdeps, expected);
+            // automatic module
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd2)) {
+            jdeps.appModulePath(MODS_DIR.toString())
+                .addmods(Set.of("ALL-MODULE-PATH"))
+                .requires(Set.of(name));
+
+            runJdeps(jdeps, expected);
+        }
     }
 
     @DataProvider(name = "testpackage")
@@ -162,15 +164,15 @@
 
     @Test(dataProvider = "testpackage")
     public void testpackage(String name, String[][] expected) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -modulepath %s -package %s -addmods %s%n",
-                MODS_DIR, name, modules.stream().collect(Collectors.joining(","))
-        ));
-        jdeps.appModulePath(MODS_DIR.toString())
-            .addmods(modules)
-            .matchPackages(Set.of(name));
+        String cmd = String.format("jdeps -inverse -modulepath %s -package %s -addmods %s%n",
+            MODS_DIR, name, modules.stream().collect(Collectors.joining(",")));
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.appModulePath(MODS_DIR.toString())
+                .addmods(modules)
+                .matchPackages(Set.of(name));
 
-        runJdeps(jdeps, expected);
+            runJdeps(jdeps, expected);
+        }
     }
 
     @DataProvider(name = "testregex")
@@ -193,16 +195,16 @@
 
     @Test(dataProvider = "testregex")
     public void testregex(String name, String[][] expected) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -modulepath %s -regex %s -addmods %s%n",
-                MODS_DIR, name, modules.stream().collect(Collectors.joining(",")))
-        );
+        String cmd = String.format("jdeps -inverse -modulepath %s -regex %s -addmods %s%n",
+                MODS_DIR, name, modules.stream().collect(Collectors.joining(",")));
 
-        jdeps.appModulePath(MODS_DIR.toString())
-             .addmods(modules)
-             .regex(name);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.appModulePath(MODS_DIR.toString())
+                .addmods(modules)
+                .regex(name);
 
-        runJdeps(jdeps, expected);
+            runJdeps(jdeps, expected);
+        }
     }
 
     @DataProvider(name = "classpath")
@@ -237,26 +239,26 @@
             .collect(Collectors.joining(File.pathSeparator));
 
         Path jarfile = LIBS_DIR.resolve("m7.jar");
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -classpath %s -regex %s %s%n",
-                cpath, name, jarfile)
-        );
-        jdeps.verbose("-verbose:class")
-             .addClassPath(cpath)
-             .regex(name).addRoot(jarfile);
-        runJdeps(jdeps, expected);
+
+        String cmd1 = String.format("jdeps -inverse -classpath %s -regex %s %s%n",
+            cpath, name, jarfile);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd1)) {
+            jdeps.verbose("-verbose:class")
+                .addClassPath(cpath)
+                .regex(name).addRoot(jarfile);
+            runJdeps(jdeps, expected);
+        }
 
         // all JAR files on the command-line arguments
         Set<Path> paths = modules.stream()
-            .map(mn -> LIBS_DIR.resolve(mn + ".jar"))
-            .collect(Collectors.toSet());
-        jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -inverse -regex %s %s%n", name, paths)
-        );
-        jdeps.verbose("-verbose:class").regex(name);
-        paths.forEach(jdeps::addRoot);
-        runJdeps(jdeps, expected);
-
+                                 .map(mn -> LIBS_DIR.resolve(mn + ".jar"))
+                                 .collect(Collectors.toSet());
+        String cmd2 = String.format("jdeps -inverse -regex %s %s%n", name, paths);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd2)) {
+            jdeps.verbose("-verbose:class").regex(name);
+            paths.forEach(jdeps::addRoot);
+            runJdeps(jdeps, expected);
+        }
     }
 
     private void runJdeps(JdepsUtil.Command jdeps, String[][] expected)  throws Exception {
@@ -292,7 +294,6 @@
 
             assertFalse(noneMatched);
         }
-
     }
 
 }
--- a/langtools/test/tools/jdeps/modules/ModuleTest.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/ModuleTest.java	Fri May 20 09:47:00 2016 -0700
@@ -151,30 +151,30 @@
         throws IOException
     {
         // jdeps -modulepath <modulepath> -m root paths
+        String cmd = String.format("jdeps -modulepath %s -addmods %s %s%n",
+            MODS_DIR, roots.stream().collect(Collectors.joining(",")), paths);
 
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -modulepath %s -addmods %s %s%n", MODS_DIR,
-                          roots.stream().collect(Collectors.joining(",")), paths)
-        );
-        jdeps.appModulePath(modulepath)
-             .addmods(roots);
-        Arrays.stream(paths).forEach(jdeps::addRoot);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.appModulePath(modulepath)
+                .addmods(roots);
+            Arrays.stream(paths).forEach(jdeps::addRoot);
 
-        // run the analyzer
-        DepsAnalyzer analyzer = jdeps.getDepsAnalyzer();
-        assertTrue(analyzer.run());
+            // run the analyzer
+            DepsAnalyzer analyzer = jdeps.getDepsAnalyzer();
+            assertTrue(analyzer.run());
 
-        // analyze result
-        Graph<DepsAnalyzer.Node> g1 = analyzer.moduleGraph();
-        g1.nodes().stream()
-            .filter(u -> u.name.equals(data.moduleName))
-            .forEach(u -> data.checkRequires(u.name, g1.adjacentNodes(u)));
+            // analyze result
+            Graph<DepsAnalyzer.Node> g1 = analyzer.moduleGraph();
+            g1.nodes().stream()
+                .filter(u -> u.name.equals(data.moduleName))
+                .forEach(u -> data.checkRequires(u.name, g1.adjacentNodes(u)));
 
-        Graph<DepsAnalyzer.Node> g2 = analyzer.dependenceGraph();
-        g2.nodes().stream()
-            .filter(u -> u.name.equals(data.moduleName))
-            .forEach(u -> data.checkDependences(u.name, g2.adjacentNodes(u)));
+            Graph<DepsAnalyzer.Node> g2 = analyzer.dependenceGraph();
+            g2.nodes().stream()
+                .filter(u -> u.name.equals(data.moduleName))
+                .forEach(u -> data.checkDependences(u.name, g2.adjacentNodes(u)));
 
-        jdeps.dumpOutput(System.err);
+            jdeps.dumpOutput(System.err);
+        }
     }
 }
--- a/langtools/test/tools/jdeps/modules/SplitPackage.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/SplitPackage.java	Fri May 20 09:47:00 2016 -0700
@@ -70,36 +70,35 @@
     }
 
     private void runTest(String root, String... splitPackages) throws Exception {
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -verbose:class -addmods %s %s%n",
-                          root, CLASSES_DIR)
-        );
-        jdeps.verbose("-verbose:class")
-            .addRoot(CLASSES_DIR);
-        if (root != null)
-            jdeps.addmods(Set.of(root));
+        String cmd = String.format("jdeps -verbose:class -addmods %s %s%n",
+            root, CLASSES_DIR);
 
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.verbose("-verbose:class")
+                .addRoot(CLASSES_DIR);
+            if (root != null)
+                jdeps.addmods(Set.of(root));
 
-        JdepsConfiguration config = jdeps.configuration();
-        Map<String, Set<String>> pkgs = config.splitPackages();
+            JdepsConfiguration config = jdeps.configuration();
+            Map<String, Set<String>> pkgs = config.splitPackages();
 
-        final Set<String> expected;
-        if (splitPackages != null) {
-            expected = Arrays.stream(splitPackages).collect(Collectors.toSet());
-        } else {
-            expected = Collections.emptySet();
-        }
+            final Set<String> expected;
+            if (splitPackages != null) {
+                expected = Arrays.stream(splitPackages).collect(Collectors.toSet());
+            } else {
+                expected = Collections.emptySet();
+            }
 
-        if (!pkgs.keySet().equals(expected)) {
-            throw new RuntimeException(splitPackages.toString());
+            if (!pkgs.keySet().equals(expected)) {
+                throw new RuntimeException(splitPackages.toString());
+            }
+
+            // java.annotations.common is not observable
+            DepsAnalyzer analyzer = jdeps.getDepsAnalyzer();
+
+            assertTrue(analyzer.run());
+
+            jdeps.dumpOutput(System.err);
         }
-
-        // java.annotations.common is not observable
-        DepsAnalyzer analyzer = jdeps.getDepsAnalyzer();
-
-        assertTrue(analyzer.run());
-
-        jdeps.dumpOutput(System.err);
     }
-
 }
--- a/langtools/test/tools/jdeps/modules/TransitiveDeps.java	Thu May 19 17:34:05 2016 -0700
+++ b/langtools/test/tools/jdeps/modules/TransitiveDeps.java	Fri May 20 09:47:00 2016 -0700
@@ -122,30 +122,31 @@
     @Test(dataProvider = "modules")
     public void testModulePath(String name, List<ModuleMetaData> data) throws IOException {
         Set<String> roots = Set.of("m6", "unsafe");
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -modulepath %s -addmods %s -m %s%n", MODS_DIR,
-                          roots.stream().collect(Collectors.joining(",")), name)
-        );
-        jdeps.verbose("-verbose:class")
-             .appModulePath(MODS_DIR.toString())
-             .addmods(roots)
-             .addmods(Set.of(name));
 
-        runJdeps(jdeps, data);
+        String cmd1 = String.format("jdeps -modulepath %s -addmods %s -m %s%n", MODS_DIR,
+            roots.stream().collect(Collectors.joining(",")), name);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd1)) {
+            jdeps.verbose("-verbose:class")
+                .appModulePath(MODS_DIR.toString())
+                .addmods(roots)
+                .addmods(Set.of(name));
 
+            runJdeps(jdeps, data);
+        }
         // run automatic modules
         roots = Set.of("ALL-MODULE-PATH", "jdk.unsupported");
 
-        jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -modulepath %s -addmods %s -m %s%n", LIBS_DIR,
-                          roots.stream().collect(Collectors.joining(",")), name)
-        );
-        jdeps.verbose("-verbose:class")
-            .appModulePath(LIBS_DIR.toString())
-            .addmods(roots)
-            .addmods(Set.of(name));
+        String cmd2 = String.format("jdeps -modulepath %s -addmods %s -m %s%n", LIBS_DIR,
+            roots.stream().collect(Collectors.joining(",")), name);
 
-        runJdeps(jdeps, data);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd2)) {
+            jdeps.verbose("-verbose:class")
+                .appModulePath(LIBS_DIR.toString())
+                .addmods(roots)
+                .addmods(Set.of(name));
+
+            runJdeps(jdeps, data);
+        }
     }
 
     @DataProvider(name = "jars")
@@ -170,14 +171,15 @@
             .collect(Collectors.joining(File.pathSeparator));
 
         Path jarfile = LIBS_DIR.resolve(name + ".jar");
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -classpath %s %s%n", cpath, jarfile)
-        );
-        jdeps.verbose("-verbose:class")
-             .addClassPath(cpath)
-             .addRoot(jarfile);
 
-        runJdeps(jdeps, data);
+        String cmd = String.format("jdeps -classpath %s %s%n", cpath, jarfile);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.verbose("-verbose:class")
+                .addClassPath(cpath)
+                .addRoot(jarfile);
+
+            runJdeps(jdeps, data);
+        }
     }
 
     @DataProvider(name = "compileTimeView")
@@ -225,15 +227,14 @@
 
         Path jarfile = LIBS_DIR.resolve(name + ".jar");
 
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -ct -classpath %s %s%n", cpath, jarfile)
-        );
+        String cmd = String.format("jdeps -ct -classpath %s %s%n", cpath, jarfile);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.verbose("-verbose:class")
+                .addClassPath(cpath)
+                .addRoot(jarfile);
 
-        jdeps.verbose("-verbose:class")
-             .addClassPath(cpath)
-             .addRoot(jarfile);
-
-        runJdeps(jdeps, data, true, 0 /* -recursive */);
+            runJdeps(jdeps, data, true, 0 /* -recursive */);
+        }
     }
 
     @DataProvider(name = "recursiveDeps")
@@ -276,14 +277,14 @@
 
         Path jarfile = LIBS_DIR.resolve(name + ".jar");
 
-        JdepsUtil.Command jdeps = JdepsUtil.newCommand(
-            String.format("jdeps -R -classpath %s %s%n", cpath, jarfile)
-        );
-        jdeps.verbose("-verbose:class").filter("-filter:archive")
-             .addClassPath(cpath)
-             .addRoot(jarfile);
+        String cmd = String.format("jdeps -R -classpath %s %s%n", cpath, jarfile);
+        try (JdepsUtil.Command jdeps = JdepsUtil.newCommand(cmd)) {
+            jdeps.verbose("-verbose:class").filter("-filter:archive")
+                .addClassPath(cpath)
+                .addRoot(jarfile);
 
-        runJdeps(jdeps, data, true, 0 /* -recursive */);
+            runJdeps(jdeps, data, true, 0 /* -recursive */);
+        }
     }
 
     private void runJdeps(JdepsUtil.Command jdeps, List<ModuleMetaData> data)
@@ -322,6 +323,5 @@
                 ModuleMetaData md = dataMap.get(u.name);
                 md.checkDependences(u.name, g2.adjacentNodes(u));
             });
-
     }
 }