How to remove a module in Java 9?

I have three modules: module-a, module-b, module-c. Module-a and module-b are in the boot layer. I create a layer for module-c myself. Module-c has a JPMS implementation of the service whose interface is in module-a.

So I create a layer with module-c in module-b.

ModuleFinder finder = ModuleFinder.of(moduleCPath); ModuleLayer parent = ModuleLayer.boot(); Configuration cf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("module-c")); ClassLoader scl = ClassLoader.getSystemClassLoader(); ModuleLayer layer = parent.defineModulesWithOneLoader(cf, scl); 

Then in module-b, I call the service from module-c. After completing the service, I no longer need module-c and the newly created layer. How to remove it from the JVM and free all resources? Is layer = null; enough to do layer = null; ?

+5
source share
2 answers

The module level, modules in the layer, and class loaders that support the layer can be GC'ed / unloaded when they are no longer available.

If you want to prove this to yourself, create a weak link to the layer object and you will see that the link is cleared (and queued if you use the link queue) when the GC'ed layer.

+5
source

An EMPTY_LAYER should solve your use case (from one of the comments on the question, trying to assign new HashSet<> as roots) here, where links to other layers are no longer processed inside the created layer :

 layer = ModuleLayer.empty(); 

Returns an empty layer. There are no modules in the empty layer. It has no parents.


Due to the fact that I can explicitly remove the layer from the JVM, I would not expect such an API to be open publicly, since the JVM must have at least one non-empty layer, the boot layer , which is created when the Java virtual machine starts.

And if such a method is open, I wonder if users can try and remove this layer. Although I am trying to be technically hypothetical from this perspective.

+2
source

Source: https://habr.com/ru/post/1271961/


All Articles