@Experimental JIT service index: let a packager supply precomputed service discovery on the JVM
Feature description
Add an @Experimental, data-only service index that a packager can register through StaticOptimizations. On the JVM, service loading would then skip the META-INF/services and META-INF/micronaut scan for the types the index covers. Core keeps its own instantiation, error mapping and fork-join fan-out. Native image already works this way through its ImageSingletons table; the JVM has no equivalent. Nothing changes unless a producer registers an index. Target: 5.3.0.
Found while profiling the startup of micronaut-runner with its benchmark-large sample: 379 bean definitions, 49 dependency JARs and 431 META-INF/micronaut service entries across four service types. A packager already sees the closed class path, so it can precompute discovery. Today nothing on the JVM can consume the result.
Current state (5.3.x)
- Native:
ServiceLoaderFeaturebuilds a table, whichServiceScannerreads only throughImageSingletons. - JVM: every lookup scans.
ServiceEntriesLoadercallsgetResources("META-INF/services/<type>"), parses each URL, then appends theMETA-INF/micronautentries (L157-L177).BeanDefinitionReferenceandBeanConfigurationread onlyMETA-INF/micronaut, throughfindMetaMicronautServiceEntries. - The only JVM hook is per type:
SoftServiceLoader.Optimizations.- A producer has to re-implement instantiation, ordering and fan-out, and the default
loadis sequential. - Nothing fills this hook on the JVM. micronaut-projects/micronaut-aot#423 removed AOT's 2.x
serviceloading.jitgenerator in 3.0.0-M2, for three reasons: no measurable benefit, complexity, and breakage on Micronaut 5. That generator used parallel streams and lambdas and pruned by@Requires. - The Gradle plugin's
optimizeServiceLoadingflag only logs a warning. - This proposal is smaller: names only, no pruning, and core keeps instantiation and fan-out.
- A producer has to re-implement instantiation, ordering and fan-out, and the default
Measurements
Prototype. A names-only table (28 types, 489 names) was registered through today's hook. Each type's loader forks one task per name and joins the tasks in order, and each task instantiates the class the way core does. So only discovery is precomputed. The "off" arm is the same JAR with the prototype's kill switch set.
Method. Time from spawn to the first HTTP 200 on /hello, over interleaved rounds (random order, 3 warm-up rounds). Each figure is the median paired difference with a bootstrap 95% CI. OpenJDK 25.0.4.1 on macOS arm64 with 12 CPUs, on a shared, loaded host. "With JDK AOT cache" means -XX:AOTCache, with each arm trained in its own mode.
| Packaging and core | Rounds | Uncached | With JDK AOT cache |
|---|---|---|---|
| Shadow, core 5.2.2 classes (other modules 5.1.15) | 70 | −6.2 ms [−10.2, −1.5] | −6.4 ms [−10.0, −2.7] |
| Shadow, 5.1.15 | 30 | −14.6 ms [−20.2, −7.1] | −9.3 ms [−16.9, −3.8] |
| micronaut-runner nested JAR, 5.1.15 | 30 | −9.9 ms [−17.6, −7.1] | −7.1 ms [−9.3, −3.0] |
- Size of the gain. The 5.2.2 medians were about 511 ms uncached and 228 ms cached, so the cached gain is about 2.8%. With the table on,
findAllMicronautMetaServicesnever ran. - #13121 already removed most of the 5.1 cost. 5.2.2 against 5.1.15, both without an index: −18.7 ms [−30.3, −15.2] (30 rounds). A cold probe of discovery alone (15 JVMs each) took 8.8 ms against 35.2 ms on Shadow, and 9.4 ms against 41.1 ms on a layered class path of 50 JARs.
- Names are enough. Generating direct
newcalls instead of names made no measurable difference in 3 of 4 comparisons. - The fan-out matters. A sequential version of the table was +153.6 ms [+149.4, +164.2] slower uncached (nested JAR, 5.1.15, 30 rounds).
- Not yet measured: 5.3.x, and layered or nested class paths on 5.2 or later.
Proposed change
The type. An
@Experimental, immutable record inio.micronaut.core.io.service, registered through aStaticOptimizations.Loader. It has two maps, because the JVM callers read the two sources separately:micronautServicesholds exactly whatfindAllMicronautMetaServicesreturns. It is exhaustive.standardServicesholds theMETA-INF/servicesnames for each type, in scan order. A type that is not listed is scanned.
One merged list per type, like the native table, would be wrong for
findMetaMicronautServiceEntries, which reads onlyMETA-INF/micronaut. An alternative with no new type isOptimizations.ofNames(..)on today's hook, although it would not cover directnewCollectorcallers.Where it is read.
findMicronautMetaServiceEntriesanswers frommicronautServices.ServiceEntriesLoader.computeusesstandardServicesinstead ofgetResourcesand the parse.Keep core's fan-out. Core keeps one forked task per entry, joined in order, and its instantiation. The index must not force
fork = falsethe way the native table does.Rules.
- The index is ignored in image code, where the native table wins.
- It is served only for the class loader it was built for.
- The name condition is applied to every name.
- A second index fails loudly. Today
StaticOptimizations.setlets the last writer win. - A system property switches the index off.
A new, deterministic
@Internalbuilder. It takes a class loader and a list of types, reproduces the scan, and shares its parser. It sorts directory walks, so output is reproducible.- Do not reuse
buildStaticServiceDefinitions. It putsMETA-INF/micronautfirst and merges both sources. - It also indexes
META-INF/servicesonly for the six internal types. It misses, for example,HttpRequestFactory,PropertySourceImporterandTypeInformationProvider.
- Do not reuse
@Experimental
public record ServiceIndex(Map<String, Set<String>> micronautServices, // exhaustive
Map<String, List<String>> standardServices) { // per type, scan order
}
// ServiceEntriesLoader.compute(), for an indexed type: no getResources, `fork` left as computed
for (String name : names) {
if (lineCondition.test(name)) {
ServiceInstanceLoader<S> task = new ServiceInstanceLoader<>(name, transformer);
tasks.add(task);
if (fork) { task.fork(); } else { task.compute(); }
}
}Follow-ups, to be filed once this lands
- micronaut-aot: a names-only JIT optimiser that emits only this index, with no fallback for older cores and no pruning.
- Gradle: wire
optimizeServiceLoadingto that optimiser and update its Javadoc, which still describes evaluating requirements ahead of time. - Maven: needs no flag. The option appears in the generated
aot.properties. - No
META-INF/micronautmerge for fat JARs. The entries are unique paths, so a Shadow JAR already has one directory. On benchmark-large itsMETA-INF/micronaut/holds 436 ZIP entries: the same 431 service entries plus five directory entries.
Compatibility
- Closed world: JARs added to the class path after indexing are missed for the indexed types. Producers should emit an index only for closed packagings.
- Order: discovery order is not a contract, and it already differs between Shadow, layered and nested-JAR packagings. The prototype's table, built in Runner's order, served a Shadow JAR with 6 order-only differences and unchanged behaviour.
- Lazy references: if #13393 gives entries content, the index must either carry that content or leave the type to the scan.
How to verify
- An equivalence mode: for every indexed type, the index and the scan return the same names in the same order, run against a packaged JAR.
- Tests: the fallback for missing types, the condition, the duplicate failure, the kill switch, and native image unchanged.
- Before merging: paired startup rows on 5.3.x for Shadow, a layered class path and a nested JAR.
Related
- #13388: the patch-level fixes to the static paths that this builds on. It should land first.
- micronaut-runner:
- https://github.com/alvarosanchez/micronaut-runner/issues/154 serves a names-only interim table through today's hook, and will emit this index once it exists.
- https://github.com/alvarosanchez/micronaut-runner/issues/135 packages AOT's
optimizedJitJar, so an AOT producer also reaches Runner users.
- #9816 (open) proposes prohibiting dynamic service loading. It could become the index's strict mode.
Source: micronaut-projects/micronaut-core