Sub topic 19
Module layers and dynamic loading
This chapter assumes you know module-info.java, requires, exports, the module path, and ServiceLoader with uses and provides. Everything so far resolved modules once, at startup. Layers let a running program resolve and load more modules later.
What a layer is
A module layer (java.lang.ModuleLayer) is a set of resolved modules together with the class loaders that define their classes. A layer is built in two steps:
- A configuration (
java.lang.module.Configuration) is the result of resolution. It contains the modules and their readability edges, but it has not loaded any classes. - A layer maps each module in a configuration to a class loader and defines the runtime
Moduleobjects.
When you start a modular application, the JVM builds the boot layer from the root modules and the module path. ModuleLayer.boot() returns it. You can build more layers on top of it.
ModuleLayer.boot().modules().stream()
.map(Module::getName)
.sorted()
.forEach(System.out::println);Parent layers and visibility rules
Every layer has zero or more parent layers. The boot layer's parent is the empty layer. The rules are:
- A module in a child layer can read modules in its parent layers, if resolution found the dependency there.
- A module in a parent layer never reads modules in a child layer. Parents cannot see children.
- Sibling layers cannot see each other.
- Within one layer, each module name appears once and each package belongs to one module (the split package rule still applies).
- Across layers, the same module name and the same package name can appear again. The two copies are different runtime modules with different class loaders.
That last rule is the main reason to use layers. Two versions of a library can coexist, each in its own layer, which the flat module path cannot do.
Building a layer step by step
Suppose com.example.greeter exports com.example.greeter.api.GreetingProvider. A plugin module com.example.greeter.french provides an implementation. The plugin jar sits in a plugins directory that is not on the module path, so the boot layer does not contain it.
The host module declares that it consumes the service and requires the greeter module:
// src/com.example.host/module-info.java
module com.example.host {
requires com.example.greeter;
uses com.example.greeter.api.GreetingProvider;
}The host code resolves the plugins, builds a layer, and loads providers from it:
// src/com.example.host/com/example/host/PluginHost.java
package com.example.host;
import com.example.greeter.api.GreetingProvider;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.nio.file.Path;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
public class PluginHost {
public static void main(String[] args) {
ModuleFinder finder = ModuleFinder.of(Path.of("plugins"));
List<String> roots = finder.findAll().stream()
.map(ModuleReference::descriptor)
.map(d -> d.name())
.collect(Collectors.toList());
ModuleLayer parent = ModuleLayer.boot();
Configuration cf = parent.configuration()
.resolveAndBind(finder, ModuleFinder.of(), roots);
ModuleLayer layer = parent.defineModulesWithOneLoader(
cf, ClassLoader.getSystemClassLoader());
for (GreetingProvider p : ServiceLoader.load(layer, GreetingProvider.class)) {
System.out.println(p.greet("layers"));
}
}
}Run it with the plugin jar in plugins and everything else on the module path:
javac -d out --module-source-path src -m com.example.host
java --module-path out -m com.example.host/com.example.host.PluginHostWhat each call does:
ModuleFinder.of(Path)looks for modules in a directory or jar. It does not load anything.parent.configuration().resolveAndBind(...)resolves the roots. Dependencies that the finder cannot supply are looked up in the parent configuration, so the plugin'srequires com.example.greeteris satisfied by the boot layer. Resolution fails with aFindExceptionif a dependency is missing everywhere.- The "bind" part also adds service providers that are observable and match a
usesdeclaration of a resolved module. A plainresolveskips this step. defineModulesWithOneLoadercreates one new class loader for all modules in the layer.ServiceLoader.load(layer, service)searches that layer and its ancestors for providers. The calling module must declareusesfor the service.
Choosing a class loader strategy
| Method | Class loaders created | Use when |
|---|---|---|
| `defineModulesWithOneLoader` | One for the whole layer | Modules in the layer need to cooperate and have no conflicting packages |
| `defineModulesWithManyLoaders` | One per module | You want isolation between modules inside the layer |
| `defineModules(cf, mapper)` | Whatever the function returns for each module name | You need custom loaders, for example to add extra checks or sources |
The first argument after the configuration is the parent class loader. It is used when a class is not found in the layer's own modules. Delegation to parent layers happens automatically for packages that belong to modules in those layers.
Common errors
FindException: Module X not found: the finder and the parent configuration together cannot satisfy arequires. Add the missing module to the finder, or to the parent layer.ResolutionExceptionmentioning a package in two modules: two modules in the same configuration contain the same package. Move one to a different layer or merge them.ServiceConfigurationErroror no providers found: the caller lacksuses, you usedresolveinstead ofresolveAndBindand the provider module is not a root, or the provider module is not in the layer you passed.IllegalAccessErrororInaccessibleObjectExceptionafter loading: reflection into a layer module needsopensin the plugin descriptor, orlayer.findModule("name")followed byModule.addOpensfrom code in that module.
Looking up modules in a layer
Once a layer exists, you can inspect it:
layer.findModule("com.example.greeter.french").ifPresent(m -> {
System.out.println(m.getName() + " loaded by " + m.getClassLoader());
});
System.out.println(layer.parents());findModule searches the layer and its ancestors, and layer.modules() lists only the modules defined directly in that layer. Module.getLayer() returns the layer for a named module and null for the unnamed module.
Exercise
A host module in the boot layer builds a child layer from a plugins directory, then calls ServiceLoader.load(GreetingProvider.class) with no layer argument. No providers are found, although the plugin module declares provides correctly. Why, and how do you fix it?
Show answer
The one-argument ServiceLoader.load searches the caller's class loader and the layers visible from it, which here means the boot layer. The plugin module is only in the child layer, and parents cannot see children. Pass the layer explicitly with ServiceLoader.load(layer, GreetingProvider.class). Also make sure the host declares uses for the service, and that the configuration was built with resolveAndBind (or the plugin module is listed as a root) so the provider is part of the layer.
Exercise
Two plugins need different versions of a library module named lib.json, both with the package lib.json.api. Can both be loaded in one JVM, and how?
Show answer
Yes. Put each plugin and its version of lib.json in its own layer, with the boot layer as the parent of both. Within one layer a package can belong to only one module and a module name can appear only once, but separate layers have separate class loaders, so the duplicate module and package names do not conflict. The two layers cannot see each other, which keeps the versions isolated.