Is it possible to load and unload jdk and custom modules dynamically in Java 9?

こ雲淡風輕ζ 提交于 2019-12-18 12:15:39

问题


I am beginner in JPMS and can't understand its dynamism. For example, in current JVM instance moduleA.jar is running. moduleA requires only java.base module. Now, I want

  1. to load dynamically moduleB.jar that needs java.sql module and moduleC.jar
  2. execute some code from moduleB
  3. unload moduleB, java.sql, moduleC from JVM and release all resources.

Can it be done in Java 9 module system?


回答1:


This is an advanced topic. At a high-level, the module system is not dynamic in the sense that individual modules can not be unloaded or replaced in a running VM. However, you can use the API, specifically java.lang.module.Configuration and java.lang.ModuleLayer to create dynamic configurations of modules and instantiate them in a running VM as a layer of modules. In your scenario, then you may create a layer of modules with modules B and C. This layer of modules will be GC'ed/unloaded once there are no references to them.

As I said, this is an advanced topic and it's probably better to spend time mastering the basics, including services, before getting into dynamic configurations and module layers.




回答2:


The other answer is fully correct, but please note that "in the end" these things didn't really change.

Before Java 9 you could use custom class loader instances to achieve something like this. That is for example how application servers such as Tomcat allow you to re-deploy an application - by basically throwing away a whole "context" that was initially "built" using a specific class loader instance.

With Java9, this concept is described using that layers abstraction - but in the end it still means that custom code needs to provide all the implementation of actually creating layers with different class loaders.

And for some further read on layers see this answer that I gave some time back on a similar question (which focused on how to use different versions of the same module within a single application).



来源:https://stackoverflow.com/questions/46112809/is-it-possible-to-load-and-unload-jdk-and-custom-modules-dynamically-in-java-9

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!