changeset 1371:00f2c71a3d71

Manual migration to JDK 7 language features: try-with-resources and suppressed exceptions.
author shade
date Wed, 16 Nov 2016 14:51:34 +0100
parents 0ca62574e95f
children 548d8d867582
files jmh-core/src/main/java/org/openjdk/jmh/generators/core/BenchmarkGenerator.java jmh-core/src/main/java/org/openjdk/jmh/profile/AbstractPerfAsmProfiler.java jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfAsmProfiler.java jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfNormProfiler.java jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfProfiler.java jmh-core/src/main/java/org/openjdk/jmh/profile/WinPerfAsmProfiler.java jmh-core/src/main/java/org/openjdk/jmh/runner/BaseRunner.java jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkException.java jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkHandler.java jmh-core/src/main/java/org/openjdk/jmh/runner/Runner.java jmh-core/src/main/java/org/openjdk/jmh/util/FileUtils.java jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMGeneratorSource.java
diffstat 12 files changed, 53 insertions(+), 124 deletions(-) [+]
line wrap: on
line diff
--- a/jmh-core/src/main/java/org/openjdk/jmh/generators/core/BenchmarkGenerator.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/generators/core/BenchmarkGenerator.java	Wed Nov 16 14:51:34 2016 +0100
@@ -138,7 +138,7 @@
                 entriesByQName.put(br.getUserClassQName(), br);
             }
         } catch (UnsupportedOperationException e) {
-            destination.printWarning("Unable to read the existing benchmark list, because of UnsupportedOperationException. Run on JDK 7 or higher.");
+            destination.printError("Unable to read the existing benchmark list.", e);
         }
 
         // Generate new benchmark entries
@@ -189,30 +189,24 @@
     }
 
     private Collection<String> readBenchmarkList(GeneratorDestination destination) {
-        Reader reader = null;
-        try {
-            reader = destination.getResource(BenchmarkList.BENCHMARK_LIST.substring(1));
+        String list = BenchmarkList.BENCHMARK_LIST.substring(1);
+        try (Reader reader = destination.getResource(list)) {
             return FileUtils.readAllLines(reader);
         } catch (IOException e) {
             // okay, move on
-        } finally {
-            FileUtils.safelyClose(reader);
         }
         return Collections.emptyList();
     }
 
     private void writeBenchmarkList(GeneratorDestination destination, Collection<BenchmarkListEntry> entries) {
-        PrintWriter writer = null;
-        try {
+        String list = BenchmarkList.BENCHMARK_LIST.substring(1);
+        try (PrintWriter writer = new PrintWriter(destination.newResource(list))) {
             // Write out the complete benchmark list
-            writer = new PrintWriter(destination.newResource(BenchmarkList.BENCHMARK_LIST.substring(1)));
             for (BenchmarkListEntry entry : entries) {
                 writer.println(entry.toLine());
             }
         } catch (IOException ex) {
             destination.printError("Error writing benchmark list", ex);
-        } finally {
-            FileUtils.safelyClose(writer);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/profile/AbstractPerfAsmProfiler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/profile/AbstractPerfAsmProfiler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -612,10 +612,8 @@
             String target = (saveLogToFile == null) ?
                 saveLogTo + "/" + br.getParams().id() + ".log" :
                 saveLogToFile;
-            FileOutputStream asm;
-            try {
-                asm = new FileOutputStream(target);
-                PrintWriter pwAsm = new PrintWriter(asm);
+            try (FileOutputStream asm = new FileOutputStream(target);
+                 PrintWriter pwAsm = new PrintWriter(asm)) {
                 for (ASMLine line : assembly.lines) {
                     for (String event : this.events) {
                         long count = (line.addr != null) ? events.get(event).count(line.addr) : 0;
@@ -623,9 +621,6 @@
                     }
                     pwAsm.println(line.code);
                 }
-                pwAsm.flush();
-                FileUtils.safelyClose(asm);
-
                 pw.println("Perf-annotated Hotspot log is saved to " + target);
             } catch (IOException e) {
                 pw.println("Unable to save Hotspot log to " + target);
@@ -726,16 +721,14 @@
     }
 
     Collection<Collection<String>> splitAssembly(File stdOut) {
-        FileReader in = null;
-        try {
+        try (FileReader in = new FileReader(stdOut);
+             BufferedReader br = new BufferedReader(in)) {
             Multimap<Long, String> writerToLines = new HashMultimap<>();
             Long writerId = -1L;
 
             Pattern pWriterThread = Pattern.compile("(.*)<writer thread='(.*)'>(.*)");
             String line;
 
-            in = new FileReader(stdOut);
-            BufferedReader br = new BufferedReader(in);
             while ((line = br.readLine()) != null) {
                 // Parse the writer threads IDs:
                 //    <writer thread='140703710570240'/>
@@ -760,8 +753,6 @@
             return r;
         } catch (IOException e) {
             return Collections.emptyList();
-        } finally {
-            FileUtils.safelyClose(in);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfAsmProfiler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfAsmProfiler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -77,13 +77,11 @@
 
     @Override
     protected void parseEvents() {
-        try {
+        try (FileOutputStream fos = new FileOutputStream(perfParsedData)) {
             ProcessBuilder pb = new ProcessBuilder("perf", "script", "--fields", "time,event,ip,sym,dso", "--input", perfBinData);
             Process p = pb.start();
 
             // drain streams, else we might lock up
-            FileOutputStream fos = new FileOutputStream(perfParsedData);
-
             InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fos);
             InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fos);
 
@@ -94,8 +92,6 @@
 
             errDrainer.join();
             outDrainer.join();
-
-            FileUtils.safelyClose(fos);
         } catch (IOException | InterruptedException ex) {
             throw new IllegalStateException(ex);
         }
@@ -103,13 +99,10 @@
 
     @Override
     protected PerfEvents readEvents(double skipSec) {
-        FileReader fr = null;
-        try {
+        try (FileReader fr = new FileReader(perfParsedData);
+             BufferedReader reader = new BufferedReader(fr)) {
             Deduplicator<MethodDesc> dedup = new Deduplicator<>();
 
-            fr = new FileReader(perfParsedData);
-            BufferedReader reader = new BufferedReader(fr);
-
             Multimap<MethodDesc, Long> methods = new HashMultimap<>();
             Map<String, Multiset<Long>> events = new LinkedHashMap<>();
             for (String evName : this.events) {
@@ -188,8 +181,6 @@
             return new PerfEvents(this.events, events, methodMap);
         } catch (IOException e) {
             return new PerfEvents(events);
-        } finally {
-            FileUtils.safelyClose(fr);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfNormProfiler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfNormProfiler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -197,10 +197,8 @@
     private Collection<? extends Result> process(BenchmarkResult br, File stdOut, File stdErr) {
         Multiset<String> events = new HashMultiset<>();
 
-        FileReader fr = null;
-        try {
-            fr = new FileReader(stdErr);
-            BufferedReader reader = new BufferedReader(fr);
+        try (FileReader fr = new FileReader(stdErr);
+             BufferedReader reader = new BufferedReader(fr)) {
 
             long delayNs = getDelay(br);
 
@@ -314,8 +312,6 @@
 
         } catch (IOException e) {
             throw new IllegalStateException(e);
-        } finally {
-            FileUtils.safelyClose(fr);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfProfiler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/profile/LinuxPerfProfiler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -127,10 +127,8 @@
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
 
-        FileReader fr = null;
-        try {
-            fr = new FileReader(stdErr);
-            BufferedReader reader = new BufferedReader(fr);
+        try (FileReader fr = new FileReader(stdErr);
+             BufferedReader reader = new BufferedReader(fr)) {
 
             long cycles = 0;
             long insns = 0;
@@ -181,8 +179,6 @@
             );
         } catch (IOException e) {
             throw new IllegalStateException(e);
-        } finally {
-            FileUtils.safelyClose(fr);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/profile/WinPerfAsmProfiler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/profile/WinPerfAsmProfiler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -179,13 +179,10 @@
 
     @Override
     protected PerfEvents readEvents(double skipSec) {
-        FileReader fr = null;
-        try {
+        try (FileReader fr = new FileReader(perfParsedData);
+             BufferedReader reader = new BufferedReader(fr)) {
             Deduplicator<MethodDesc> dedup = new Deduplicator<>();
 
-            fr = new FileReader(perfParsedData);
-            BufferedReader reader = new BufferedReader(fr);
-
             Multimap<MethodDesc, Long> methods = new HashMultimap<>();
             Map<String, Multiset<Long>> events = new LinkedHashMap<>();
             for (String evName : this.events) {
@@ -259,8 +256,6 @@
             return new PerfEvents(this.events, events, methodMap);
         } catch (IOException e) {
             return new PerfEvents(events);
-        } finally {
-            FileUtils.safelyClose(fr);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/runner/BaseRunner.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/runner/BaseRunner.java	Wed Nov 16 14:51:34 2016 +0100
@@ -149,7 +149,9 @@
         } catch (BenchmarkException be) {
             out.println("<failure>");
             out.println("");
-            out.println(Utils.throwableToString(be.getCause()));
+            for (Throwable cause : be.getSuppressed()) {
+                out.println(Utils.throwableToString(cause));
+            }
             out.println("");
 
             if (options.shouldFailOnError().orElse(Defaults.FAIL_ON_ERROR)) {
--- a/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkException.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkException.java	Wed Nov 16 14:51:34 2016 +0100
@@ -24,6 +24,9 @@
  */
 package org.openjdk.jmh.runner;
 
+import java.util.Collection;
+import java.util.Collections;
+
 /**
  * Internal exception in JMH. Always wraps the real cause.
  */
@@ -31,10 +34,18 @@
     private static final long serialVersionUID = 4064666042830679837L;
 
     public BenchmarkException(Throwable ex) {
-        super(ex);
+        this("Benchmark error", Collections.singleton(ex));
     }
 
-    public BenchmarkException(String msg, Throwable ex) {
-        super(msg, ex);
+    public BenchmarkException(String msg, Collection<Throwable> errors) {
+        super(msg);
+        for (Throwable err : errors) {
+            addSuppressed(err);
+        }
+    }
+
+    @Override
+    public Throwable getCause() {
+        throw new UnsupportedOperationException("BenchmarkException only has suppressed causes");
     }
 }
--- a/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkHandler.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/runner/BenchmarkHandler.java	Wed Nov 16 14:51:34 2016 +0100
@@ -207,15 +207,12 @@
         },
 
         /**
-         * Use new ForkJoinPool (JDK 7+)
+         * Use ForkJoinPool.
          */
         FJP {
             @Override
             ExecutorService createExecutor(int maxThreads, String prefix) throws Exception {
-                // (Aleksey):
-                // requires some of the reflection magic to untie from JDK 7 compile-time dependencies
-                Constructor<?> c = Class.forName("java.util.concurrent.ForkJoinPool").getConstructor(int.class);
-                return (ExecutorService) c.newInstance(maxThreads);
+                return new ForkJoinPool(maxThreads);
             }
         },
 
@@ -428,13 +425,7 @@
         stopProfilers(benchmarkParams, params, result);
 
         if (!errors.isEmpty()) {
-            Throwable first = errors.get(0);
-            if (errors.size() > 1) {
-                // TODO: Once we switch to JDK 7, make use of #addSupressed.
-                throw new BenchmarkException(errors.size() + " pending exceptions, reporting the first", first);
-            } else {
-                throw new BenchmarkException(first);
-            }
+            throw new BenchmarkException("Benchmark error during the run", errors);
         }
 
         return result;
--- a/jmh-core/src/main/java/org/openjdk/jmh/runner/Runner.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/runner/Runner.java	Wed Nov 16 14:51:34 2016 +0100
@@ -556,7 +556,7 @@
             out.endRun(runResults);
             return runResults;
         } catch (BenchmarkException be) {
-            throw new RunnerException("Benchmark caught the exception", be.getCause());
+            throw new RunnerException("Benchmark caught the exception", be);
         }
     }
 
@@ -706,15 +706,11 @@
 
     private List<IterationResult> doFork(BinaryLinkServer reader, List<String> commandString,
                                                               File stdOut, File stdErr, boolean printOut, boolean printErr) {
-        FileOutputStream fosErr = null;
-        FileOutputStream fosOut = null;
-        try {
+        try (FileOutputStream fosErr = new FileOutputStream(stdErr);
+             FileOutputStream fosOut = new FileOutputStream(stdOut)) {
             ProcessBuilder pb = new ProcessBuilder(commandString);
             Process p = pb.start();
 
-            fosErr = new FileOutputStream(stdErr);
-            fosOut = new FileOutputStream(stdOut);
-
             // drain streams, else we might lock up
             InputStreamDrainer errDrainer = new InputStreamDrainer(p.getErrorStream(), fosErr);
             InputStreamDrainer outDrainer = new InputStreamDrainer(p.getInputStream(), fosOut);
@@ -774,9 +770,6 @@
             out.println("<host VM has been interrupted waiting for forked VM: " + ex.getMessage() + ">");
             out.println("");
             throw new BenchmarkException(ex);
-        } finally {
-            FileUtils.safelyClose(fosErr);
-            FileUtils.safelyClose(fosOut);
         }
     }
 
--- a/jmh-core/src/main/java/org/openjdk/jmh/util/FileUtils.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-core/src/main/java/org/openjdk/jmh/util/FileUtils.java	Wed Nov 16 14:51:34 2016 +0100
@@ -53,12 +53,9 @@
      * @throws IOException if things go crazy
      */
     public static File extractFromResource(String name) throws IOException {
-        InputStream fis = null;
-        OutputStream fos = null;
-        try {
-            File temp = FileUtils.tempFile("extracted");
-            fis = FileUtils.class.getResourceAsStream(name);
-            fos = new FileOutputStream(temp);
+        File temp = FileUtils.tempFile("extracted");
+        try (InputStream fis = FileUtils.class.getResourceAsStream(name);
+             OutputStream fos = new FileOutputStream(temp)) {
 
             byte[] buf = new byte[8192];
             int read;
@@ -69,9 +66,6 @@
             fos.close();
 
             return temp;
-        } finally {
-            FileUtils.safelyClose(fis);
-            FileUtils.safelyClose(fos);
         }
     }
 
@@ -96,10 +90,9 @@
     }
 
     public static Collection<String> tail(File file, int num) throws IOException {
-        FileInputStream fis = null;
-        try {
-            fis = new FileInputStream(file);
-            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
+        try (FileInputStream fis = new FileInputStream(file);
+             InputStreamReader is = new InputStreamReader(fis);
+             BufferedReader reader = new BufferedReader(is)) {
             LinkedList<String> lines = new LinkedList<>();
             String line;
             while ((line = reader.readLine()) != null) {
@@ -109,8 +102,6 @@
                 }
             }
             return lines;
-        } finally {
-            FileUtils.safelyClose(fis);
         }
     }
 
@@ -125,35 +116,25 @@
     }
 
     public static Collection<String> readAllLines(File file) throws IOException {
-        FileReader fr = null;
-        try {
-            fr = new FileReader(file);
+        try (FileReader fr = new FileReader(file)) {
             return readAllLines(fr);
-        } finally {
-            FileUtils.safelyClose(fr);
         }
     }
 
     public static Collection<String> readAllLines(InputStream stream) throws IOException {
-        InputStreamReader reader = new InputStreamReader(stream);
-        try {
+        try (InputStreamReader reader = new InputStreamReader(stream)) {
             return readAllLines(reader);
         } finally {
-            FileUtils.safelyClose(reader);
             FileUtils.safelyClose(stream);
         }
     }
 
     public static void writeLines(File file, Collection<String> lines) throws IOException {
-        PrintWriter pw = null;
-        try {
-            pw = new PrintWriter(file);
+        try (PrintWriter pw = new PrintWriter(file)) {
             for (String line : lines) {
                 pw.println(line);
             }
             pw.close();
-        } finally {
-            FileUtils.safelyClose(pw);
         }
     }
 
@@ -197,12 +178,8 @@
     }
 
     public static void copy(String src, String dst) throws IOException {
-        FileInputStream fis = null;
-        FileOutputStream fos = null;
-        try {
-            fis = new FileInputStream(src);
-            fos = new FileOutputStream(dst);
-
+        try (FileInputStream fis = new FileInputStream(src);
+             FileOutputStream fos = new FileOutputStream(dst)) {
             byte[] buf = new byte[8192];
             int read;
             while ((read = fis.read(buf)) != -1) {
@@ -210,9 +187,6 @@
             }
 
             fos.close();
-        } finally {
-            FileUtils.safelyClose(fis);
-            FileUtils.safelyClose(fos);
         }
     }
 
--- a/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMGeneratorSource.java	Wed Nov 16 11:40:00 2016 +0100
+++ b/jmh-generator-asm/src/main/java/org/openjdk/jmh/generators/asm/ASMGeneratorSource.java	Wed Nov 16 14:51:34 2016 +0100
@@ -27,7 +27,6 @@
 import org.objectweb.asm.ClassReader;
 import org.openjdk.jmh.generators.core.ClassInfo;
 import org.openjdk.jmh.generators.core.GeneratorSource;
-import org.openjdk.jmh.util.FileUtils;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -50,12 +49,8 @@
     }
 
     public void processClass(File classFile) throws IOException {
-        FileInputStream fis = null;
-        try {
-            fis = new FileInputStream(classFile);
+        try (FileInputStream fis = new FileInputStream(classFile)){
             processClass(fis);
-        } finally {
-            FileUtils.safelyClose(fis);
         }
     }