Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a loaded JAR be deleted by the Java-Process?

Hello I have following Problem:

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();
    }

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

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

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?

like image 448
Christian Kuetbach Avatar asked Mar 09 '26 19:03

Christian Kuetbach


1 Answers

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

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.

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.

like image 53
Jonathan Avatar answered Mar 12 '26 09:03

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!