Dynamic loading and unloading of jar

拜拜、爱过 提交于 2019-12-25 08:57:14

问题


We have a java based (jersey+grizzly) REST Server which exposes calls like
foo.com/{game}/rules
foo.com/{game}/players
foo.com/{game}/matches


There can be arbitrary number of games
Each game has different implementations for rules, players, matches
For historical reasons, we would want separate jars for each game implementation


So there is REST Server
as and when there is a call like foo.com/tennis/rules
we want the REST Server to dynamically load 'tennis' jar. The jar does its operation. Then jar should be unloaded
If the next call was for foo.com/football/players we want the REST Server to dynamically load 'football' jar. The jar does its operation. Then jar should be unloaded


Is there a technique to do this ?
Apparently there is a very old question around [this]: java: is there a framework that allows dynamically loading and unloading of jars (but not osgi)?


回答1:


I don't know how it works on Java 8, but unloading a class in Java 7 requires unloading not only the class, but its loader, along with all references from other objects that this class might have.

Once all of them were unloaded the System.gc will be called. If other classes are still holding references then the gc won't do its job.

OSGI (as suggested by @Joop Eggen) is a viable option. JRebel, is not.




回答2:


proxy-object proxy-object library

Load java jar files dynamically in isolated class loader to avoid dependency conflicts and enable modular updates. All jar files in the [main jar folder]/lib/myLib/2.0/*.jar will be loaded.

Code Examples

Create Object from a JAR file located in the myLib/2.0 folder:

    File libDir = new File("myLib/2.0");

    ProxyCallerInterface caller = ObjectBuilder.builder()
            .setClassName("net.proxy.lib.test.LibClass")
            .setArtifact(DirArtifact.builder()
                    .withClazz(ObjectBuilderTest.class)
                    .withVersionInfo(newVersionInfo(libDir))
                    .build())
            .build();
    String version = caller.call("getLibVersion").asString();


来源:https://stackoverflow.com/questions/23625764/dynamic-loading-and-unloading-of-jar

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