From a58f7a206f75690d817280376d519f016abbb4cb Mon Sep 17 00:00:00 2001 From: Ian Levesque Date: Tue, 23 Apr 2024 19:20:34 -0400 Subject: [PATCH] Make ClasspathResolver thread-safe We run mustache with huge parallelism in buck2 and as described in https://issuetracker.google.com/issues/137929327 and https://bugs.openjdk.java.net/browse/JDK-8205976 using getResourceAsStream can sometimes be not thread-safe, such as when used with URLClassLoader. This applies the suggested workaround, which resolves the issue. --- .../resolver/ClasspathResolver.java | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/compiler/src/main/java/com/github/mustachejava/resolver/ClasspathResolver.java b/compiler/src/main/java/com/github/mustachejava/resolver/ClasspathResolver.java index 3f8a5a2f..d5518444 100644 --- a/compiler/src/main/java/com/github/mustachejava/resolver/ClasspathResolver.java +++ b/compiler/src/main/java/com/github/mustachejava/resolver/ClasspathResolver.java @@ -2,11 +2,7 @@ import com.github.mustachejava.MustacheResolver; -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; +import java.io.*; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -54,14 +50,15 @@ public Reader getReader(String resourceName) { return null; } } - InputStream is = ccl.getResourceAsStream(normalizeResourceName); - if (is == null) { - ClassLoader classLoader = ClasspathResolver.class.getClassLoader(); - is = classLoader.getResourceAsStream(normalizeResourceName); - } + else + resource = ClasspathResolver.class.getClassLoader().getResource(normalizeResourceName); - if (is != null) { - return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); + if (resource != null) { + try { + return new BufferedReader(new InputStreamReader(resource.openStream(), StandardCharsets.UTF_8)); + } catch (IOException e) { + return null; + } } else { return null; }