Java classLoader dilemma with locked jars

前端 未结 2 1531
自闭症患者
自闭症患者 2021-01-12 10:30

I was playing around with classLoaders in Java and noticed a strange thing. If a classLoader loads a class from a jar, this jar is locked indefinitely even if you unreferenc

相关标签:
2条回答
  • 2021-01-12 10:59

    In Java 7 URLClassLoader has a #close() method that fixes this.

    0 讨论(0)
  • 2021-01-12 11:04

    I have found an answer and a workaround.

    Based on this article and this amazing related article, it is a bad habit to use Class.forName(className, true, classLoader) because it keeps the class cached in the memory indefinitely.

    The solution was to use classLoader.loadClass(clasName) instead, then once finished, unreference the classLoader and call the garbage collector using:

    classLoader = null;
    System.gc();
    

    Hope this helps others! :)

    Background Info:

    My project was a complexe one: we had a GWT server acting as a RMI client to another server. So to create instances, GWT needed to download the classes from the server and load them. Later, GWT would resend instance to the server to persist them in database using Hibernate. In order to support hot deployment, we opted for dynamically class loading where a user would upload a jar and notifies the server who would load the classes from it and present them as available to GWT server

    0 讨论(0)
提交回复
热议问题