【问题标题】:Java JAR files locked by ClassLoader被 ClassLoader 锁定的 Java JAR 文件
【发布时间】:2018-02-12 15:19:55
【问题描述】:

我在一个临时文件夹中提取一个 WAR,并将所有类和库添加到 URLClassLoader

当我开始将类加载到类路径中时,“WEB-INF/lib/”下的 JAR 文件被 JVM 锁定。

完成工作后,我关闭类路径,调用 GC 并删除临时目录。

删除临时目录时,可以删除“WEB-INF/lib”下的JAR文件以外的所有文件。

我的代码:

@Override
public void generateRegressionTestClasses(Path fileJARorWarSolution, List<String> canonicalNameClassesToGenerateTests) throws Exception {

    Path tempPath = null;
    URLClassLoader classLoader = null;
    TryTest tryTest = null;
    RDP execution = null;
    try {
        // This extracts the JAR/WAR and prepares the URLClassLoader.
        GenFilterResponse response = genFilterClass.runGenFilterClass(path);

        classLoader = response.getCl();
        tempPath = response.getTempPath();

        // Verify that all the Test classes is in the ClassLoader.
        // Here is where the JAR files are locked.
        for (String s : canonicalNameClassesToGenerateTests) {
            try {
                classLoader.loadClass(s);
            } catch (ClassNotFoundException e) {
                throw new CustomException(CustomTexts.ERROR_CLASS_NOT_LOADED + s);
            }
        }

        execution = new RDP();
        execution.setClassLoader(classLoader);

        TryTest = new TryTest(execution);
        tryTest.handle(null);
    } finally {
        tryTest = null;
        execution = null;
        if (classLoader != null) {
            try {
                classLoader.close();
            } catch (Exception e) {
                //
            } finally {
                classLoader = null;
                System.gc();
            }
        }
        if (tempPath != null) {
            FileSystemUtils.deleteRecursively(tempPath.toFile());
        }
    }

有人知道如何解锁这些文件吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    解决了。

    如果我使用这种 URI 将 JAR 加载到类加载器中:

    new URL("jar:file:" + jar.toAbsolutePath().toString() + "!/").toURI().toURL()
    

    示例 URI:

    jar:file:c:/myJar.jar

    ClassLoader 关闭后文件被锁定。

    如果我使用这种 URI 将 JAR 加载到类加载器中:

    warDirectory.toFile().toURI().toURL()
    

    示例 URI:

    文件:c:/myJar.jar

    当 Classloader 关闭时,我可以删除 JAR。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2019-04-19
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多