0

According to JLS §12.7 a class can be unloaded once its class loader can be reclaimed by Garbage Collection. This works in my implementation of a dynamic class loader. However, I would like to know for sure when a class has been unloaded by the GC. Can I force the GC to reclaim unused class loaders and would that simultaneously unload its previously loaded classes?

Incosistent GC behavior could cause some problems in my code.

Joopi
  • 1
  • 1
  • 2
    In a word, no. "Incosistent GC behavior could cause some problems in my code." You should *never* be relying on GC behavior for correct functioning of your code. The only guarantee is that memory is GC'd immediately, later or never. – Andy Turner Sep 16 '20 at 11:31
  • 2
    This feels like an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you explain what you're trying to do? – Andy Turner Sep 16 '20 at 11:35
  • @AndyTurner I am creating a system for dynamically loading/unloading classes to hotswap plugins on runtime. I unload classes by closing its class loader and not referencing it anywhere. However the unloading is all predicated on the GC actually cleaning up the class loader. Essentially I want to know what steps I could take to guarantee the GC actually unloads those classes. I could possibly wait until findLoadedClass(className) in the System class loader returns null... But it's a suboptimal solution. – Joopi Sep 16 '20 at 11:41
  • 1
    Why do you care about when the classes are unloaded, though? – Andy Turner Sep 16 '20 at 11:47
  • Because to "hotswap" or load a new version of said class, it must first be unloaded. As far as I know, I can't have two versions of the same class file loaded simultaneously. – Joopi Sep 16 '20 at 11:50
  • 1
    Does this help? https://stackoverflow.com/questions/11759414/java-how-to-load-different-versions-of-the-same-class#:~:text=The%20normal%20thing%20is%20classes,classes%20must%20not%20be%20there. – Andy Turner Sep 16 '20 at 11:53
  • This seems to be an appropriate solution, thank you! – Joopi Sep 16 '20 at 12:00
  • 1
    Like with every garbage collection: no, you can’t reliably force it. But if the classes are unreachable, there is no reason why it should make a difference whether they are actually unloaded or not. – Holger Sep 16 '20 at 17:52

0 Answers0