Can java process delete loaded jars?
Hello, I have the following questions:
During the unloading process, I loaded 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 terminating the JVM, the jar still exists
As a workaround, I created a temporary file and copied jar to the tempfile But now tempfile will not be deleted
I read that if classload is a GC, you can delete the loaded jar
Does anyone have any idea how to delete this file?
Solution
It depends on the operating system Windows does not allow you to delete files you are using, but Linux will delete them
One solution is to start the second process, wait for your JVM to die, and then delete the files, because even if you clear all references to the class loader that uses it, there is no guarantee that they will release the files There is no way to force object garbage collection (or even complete)
Another solution is to write a class loader that loads the jar This way, when you want to get rid of it, you can make sure that jar is closed If the only object that opens it is your classloader, you can make sure it is free and should be removable