Java-Process可以删除加载的JAR吗? [英] Can a loaded JAR be deleted by the Java-Process?

查看:370
本文介绍了Java-Process可以删除加载的JAR吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以下问题:

在卸载过程中,我加载了一个JAR(jdbc-driver)。

Within an uninstall-process I load a JAR (jdbc-driver).

    URL pDriverJar = jarToDelete.toURI().toURL();
    URL[] lURLList = new URL[]{pDriverJar};
    URLClassLoader lLoader =  new URLClassLoader(lURLList, Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(lLoader);
    Class<?> aClass = Class.forName("jdbc.Driver"); // was Oracle: oracle.jdbc.OracleDriver but should not be important

    if(jarToDelete.delete()){
        System.out.println("deleted");
    }else {
        jarToDelete.deleteOnExit();
    }

终止JVM后,jar仍然存在。

After terminiation of the JVM, the jar is still existant.

作为一个workarround,我创建了一个临时文件,并将Jar复制到该tempfile。但是现在不会删除Tempfile。

As a workarround, I've created a tempfile, and copied the Jar to that tempfile. But now the Tempfile will not be deleted.

我读过,如果ClassLoad是GC,可以删除加载的jar。

I've read, that if the ClassLoad is GC, the loaded jars can be removed.

有没有人有想法,如何删除这个文件?

Does anyone have an Idea, how to delete this File?

推荐答案

这取决于操作系统。 Windows不允许你删除正在使用的文件,但Linux会删除。

It depends on the operating system. Windows will not let you delete files that are in-use, but Linux will.

一个解决方案是启动第二个进程,等待你的JVM死掉然后删除文件,因为即使您清除了对使用它的类加载器的所有引用,也不能保证它们将释放该文件。没有办法强制对象的垃圾收集(甚至终结)。

One solution would be to start a second process that waits for your JVM to die and then deletes the file, as even if you clear all references to classloaders using it, there is no guarantee that they will release the file. There is no way to force garbage collection (or even finalization) of an object.

另一种解决方案是编写加载Jar的类加载器。这样,当你想摆脱它时,你可以确定罐子是关闭的。如果打开它的唯一对象是你的类加载器,那么你可以确定它是免费的并且应该是可删除的。

Another solution would be to write the classloader that loads the Jar. That way, when you want to get rid of it, you can be certain that the Jar is closed. If the only object that opened it was your classloader, then you can be certain it is free and should be deletable.

这篇关于Java-Process可以删除加载的JAR吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆