读取JRT后如何释放全部资源?JRTFS读取Java模块列表内存泄漏修复
问题描述
我需要通过指定Java Home读取Java 9+版本安装环境中的可用模块列表,参考了相关方法实现。
该方案可正常运行,但读取Java Runtime Image时分配的资源始终无法释放,会引发内存泄漏,该问题可通过VisualVM观测到:
请问如何修复以下复现代码中的内存泄漏问题?
package leak; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Map; import java.util.stream.Stream; public class JrtfsLeak { public static void main(String[] args) throws Exception { Path javaHome = Paths.get(args[0]); for (int i = 0; i < 100000; ++i) { modules(javaHome).close(); } } private static Stream<Path> modules(Path javaHome) throws Exception { Map<String, String> env = Collections.singletonMap("java.home", javaHome.toString()); Path jrtfsJar = javaHome.resolve("lib").resolve("jrt-fs.jar"); try (URLClassLoader classloader = new URLClassLoader(new URL[] { jrtfsJar.toUri().toURL() })) { try (FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), env, classloader)) { Path modulesRoot = fs.getPath("modules"); return Files.list(modulesRoot); } } } }
问题根因
代码存在两个核心问题触发内存泄漏:
- 资源关闭顺序错误:
Files.list()返回的Stream<Path>绑定了当前FileSystem的目录资源,你在modules方法内部使用try-with-resources,会在返回Stream前就提前关闭FileSystem和ClassLoader,导致返回的Stream关联的底层资源已经失效,后续调用Stream的close方法也无法正常释放残留引用。 - 重复创建资源无复用:每次调用
modules方法都新建URLClassLoader和FileSystem实例,而jrt-fs的实现逻辑中,部分类静态资源会持有类加载器的引用,导致类加载器无法被GC,最终引发内存泄漏。
修复方案
方案一:方法内完成资源读取,不返回绑定资源的Stream
直接在方法内部将模块列表收集为普通集合返回,所有资源可以在方法内正常关闭,彻底避免资源泄漏:
private static List<Path> modules(Path javaHome) throws Exception { Map<String, String> env = Collections.singletonMap("java.home", javaHome.toString()); Path jrtfsJar = javaHome.resolve("lib").resolve("jrt-fs.jar"); try (URLClassLoader classloader = new URLClassLoader(new URL[]{jrtfsJar.toUri().toURL()})) { try (FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), env, classloader); Stream<Path> moduleStream = Files.list(fs.getPath("modules"))) { // 直接在资源块内收集结果,后续不需要依赖FileSystem和ClassLoader return moduleStream.toList(); } } }
对应的main方法也同步修改:
public static void main(String[] args) throws Exception { Path javaHome = Paths.get(args[0]); for (int i = 0; i < 100000; ++i) { List<Path> modules = modules(javaHome); // 正常处理模块列表即可 } }
方案二:复用ClassLoader和FileSystem实例
如果需要频繁读取模块列表,可以对指定Java Home对应的URLClassLoader和FileSystem做缓存,避免重复创建,从根源上减少资源生成:
// 简单缓存示例,实际使用可以根据Java Home路径做键值缓存 private static FileSystem cachedFs; private static URLClassLoader cachedLoader; private static synchronized List<Path> modules(Path javaHome) throws Exception { if (cachedFs == null) { Map<String, String> env = Collections.singletonMap("java.home", javaHome.toString()); Path jrtfsJar = javaHome.resolve("lib").resolve("jrt-fs.jar"); cachedLoader = new URLClassLoader(new URL[]{jrtfsJar.toUri().toURL()}); cachedFs = FileSystems.newFileSystem(URI.create("jrt:/"), env, cachedLoader); } try (Stream<Path> moduleStream = Files.list(cachedFs.getPath("modules"))) { return moduleStream.toList(); } } // 程序退出前统一关闭资源 private static synchronized void closeResources() throws Exception { if (cachedFs != null) { cachedFs.close(); cachedLoader.close(); cachedFs = null; cachedLoader = null; } }
两种方案都可以完全解决观测到的内存泄漏问题,如果仅需要单次读取模块列表推荐使用方案一,逻辑更简单无额外依赖;如果需要多次读取,方案二性能更优。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

