perf: cache Java version from executable.

This commit is contained in:
BBleae 2020-08-10 21:38:44 +08:00 committed by Yuhui Huang
parent 94b2cafa7a
commit c3f19d2c4a

View File

@ -30,6 +30,8 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -108,12 +110,17 @@ public final class JavaVersion {
return UNKNOWN; return UNKNOWN;
} }
private static final Map<Path, JavaVersion> fromExecutableCache = new ConcurrentHashMap<>();
public static JavaVersion fromExecutable(Path executable) throws IOException { public static JavaVersion fromExecutable(Path executable) throws IOException {
executable = executable.toRealPath();
JavaVersion cachedJavaVersion = fromExecutableCache.get(executable);
if (cachedJavaVersion != null)
return cachedJavaVersion;
Platform platform = Platform.BIT_32; Platform platform = Platform.BIT_32;
String version = null; String version = null;
executable = executable.toRealPath();
Process process = new ProcessBuilder(executable.toString(), "-version").start(); Process process = new ProcessBuilder(executable.toString(), "-version").start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
for (String line; (line = reader.readLine()) != null;) { for (String line; (line = reader.readLine()) != null;) {
@ -130,8 +137,9 @@ public final class JavaVersion {
if (parseVersion(version) == UNKNOWN) if (parseVersion(version) == UNKNOWN)
throw new IOException("Unrecognized Java version " + version); throw new IOException("Unrecognized Java version " + version);
JavaVersion javaVersion = new JavaVersion(executable, version, platform);
return new JavaVersion(executable, version, platform); fromExecutableCache.put(executable, javaVersion);
return javaVersion;
} }
private static Path getExecutable(Path javaHome) { private static Path getExecutable(Path javaHome) {