Service loading: skip ImageSingletons lookup on the JVM and apply name condition on all paths
Found while profiling micronaut-runner startup with its benchmark-large sample. It covers two small defects in io.micronaut.core.io.service and a gap in the Javadoc. The fix needs no new API, and 5.2.x has the same code, so it fits a patch release.
Expected Behavior
- Service loading on the JVM does not throw and catch an error on every scan. Outside image code,
ImageSingletons.contains(..)is alwaysfalse: nativeimage 25.3.4.1 checksImageInfo.inImageCode(), which reads the sameorg.graalvm.nativeimage.imagecodeproperty asNativeImageUtils. Skipping the lookup therefore changes no result. - The condition passed to
SoftServiceLoader.load(Class, ClassLoader, Predicate<String>)"is passed the service class name". It filters every path the same way: the JVM scan, the nativeImageSingletonstable and a registeredStaticServiceLoader.
Actual Behaviour
1. Every service scan on the JVM throws a NoClassDefFoundError.
ServiceScanner.findStaticServiceDefinitions()callsNativeImageUtils.hasImageSingletons(), which evaluatesImageSingletons.classinsidecatch (Throwable).- The GraalVM SDK is
compileOnly, so every call throws. Only the first call reaches the class loader. Each later call rethrows HotSpot's cached resolution error as a newNoClassDefFoundError. - The lookup runs twice per
META-INF/servicesscan (theServiceEntriesLoaderconstructor, thenfindMicronautMetaServiceEntriesfromcompute) and once perMETA-INF/micronaut-only lookup. - The cost is noise, not time: 22–28 errors per startup. They hit exception breakpoints and appear in JFR, because
jdk.JavaErrorThrowis on indefault.jfc.
2. Three of the four paths drop the name condition.
- a.
collectAllcallscollectStaticServices, which callsloader.load(predicate). That default passesn -> true. - b.
iterator()testss.getClass().getName().sis the entry name, so the test is always on"java.lang.String". - c. The native static branch of
ServiceEntriesLoader.computenever applieslineCondition. - d. The JVM scan tests the condition only on raw
META-INF/serviceslines.META-INF/micronautentries bypass it. The native table merges both sources, so (c) cannot be fixed consistently without (d).
Nothing in core passes a real condition, so the users affected are callers of the public three-argument load and anyone who provides a StaticServiceLoader.
3. Nothing documents that the default StaticServiceLoader.load is sequential. A prototype JIT table in micronaut-runner that loaded sequentially, like this default, was compared with the forked scan (n=30):
- +153.6 ms [+149.4, +164.2] uncached;
- +25.8 ms [+23.2, +29.9] with a JDK AOT cache.
Forking one task per entry and joining in order gave −6.7 ms [−11.9, −2.9] instead. StaticDefinition.isPresent() always returning true is not documented either.
Steps To Reproduce
- Start any Micronaut app on a JVM without the GraalVM SDK, with
-Xlog:exceptions=info, and grep the output forImageSingletons. - On the JVM,
SoftServiceLoader.load(BeanDefinitionReference.class, cl, n -> false).collectAll()still returns every reference (2d). - With a
SoftServiceLoader.Optimizationsregistered,collectAll()anditerator()ignore the condition (2a, 2b).
Measurement method. benchmark-large was packaged as a Shadow JAR and timed from spawn to the first HTTP 200 on /hello. Rounds were interleaved, paired and randomised, after 3 warm-ups. Each figure is the median paired difference with a bootstrap 95% CI.
- Diagnostic launches with
-Xlog:exceptions=infoshowed 22–28NoClassDefFoundErrors plus oneClassNotFoundExceptionper startup, and none when gated. Exception objects fell from 249 to 222. - Gate timing: +0.4 ms [−5.9, +8.2] (n=25), which is not detectable.
- The sequential figures come from the Runner-packaged JAR of the same app (n=30 per pair).
Environment Information
- macOS on Apple Silicon (12 CPUs), JDK 25.0.4.1, on a shared host.
- benchmark-large used core 5.1.15. There the lookup is a private
ServiceScanner.hasImageSingletons()that makes the same probe. #12894 moved it toNativeImageUtilsand added the Crema escape hatch; the JVM path is unchanged.
Example Application
Version
5.3.x at ea3a123 (5.3.0-SNAPSHOT). The same code is on 5.2.x (5.2.5). Measured on 5.1.15.
Proposed change
- Gate the lookup at the call site:
NativeImageUtils.inImageCode() && NativeImageUtils.hasImageSingletons().- Keep
hasImageSingletons()as it is. It is public (though@Internal), is documented as "available and enabled", and holds the Crema escape hatch. Crema runs in image code, so it still reaches that check. - No
static finalcache:io.micronaut.core.ioandio.micronaut.core.utilare initialised at build time, so a cache would hold the image builder's value.
- Keep
- Test the condition on every entry name, on every path, using the stripped name that the transformer receives.
- Call
load(condition, predicate)only when a condition was supplied, andload(predicate)otherwise. That way an implementation overriding onlyload(Predicate<S>)does not silently fall back to the sequential default. - Treat a
nulllineConditionas accept-all, becauseSoftServiceLoaderTestpassesnull.
- Call
- Document
StaticServiceLoader: the defaultloadis sequential, JIT implementations should fork one task per entry and join in order, andisPresent()is alwaystrue. Leave the public default unchanged.
--- a/core/src/main/java/io/micronaut/core/io/service/ServiceScanner.java
+++ b/core/src/main/java/io/micronaut/core/io/service/ServiceScanner.java
@@ public ServiceScanner(...)
- this.lineCondition = lineCondition;
+ this.lineCondition = lineCondition == null ? name -> true : lineCondition;
@@ findStaticServiceDefinitions()
- if (NativeImageUtils.hasImageSingletons()) {
+ if (NativeImageUtils.inImageCode() && NativeImageUtils.hasImageSingletons()) {
@@ ServiceEntriesLoader.compute(): static branch and META-INF/micronaut loop
for (String serviceEntry : serviceEntries) {
+ if (!lineCondition.test(serviceEntry)) {
+ continue;
+ }
--- a/core/src/main/java/io/micronaut/core/io/service/SoftServiceLoader.java
+++ b/core/src/main/java/io/micronaut/core/io/service/SoftServiceLoader.java
@@ collectStaticServices(...) // hasCondition = a condition was passed to load(..)
- values.addAll(loader.load(predicate));
+ values.addAll(hasCondition ? loader.load(condition, predicate) : loader.load(predicate));
@@ iterator()
- this.servicesForIterator = staticServiceLoader.findAll(s -> condition == null || condition.test(s.getClass().getName()))
+ this.servicesForIterator = staticServiceLoader.findAll(condition)Compatibility
- Change 1 gives the same result on the JVM and changes nothing in native image or Crema.
- Change 2 affects only conditions that were being ignored. Fix 2d changes JVM results for
META-INF/micronautentries when a caller passes a condition. That follows the documented contract, but it deserves a release note.
Tests
- With
org.graalvm.nativeimage.imagecodeunset,findStaticServiceDefinitions()returnsnull, and ajdk.JavaErrorThrowrecording aroundcollectAll()shows noImageSingletonserror.imageSingletonsLookupCanBeDisabledkeeps passing. - A condition that rejects one entry, tested for
collectAll,iterator()andMETA-INF/micronautentries.STATIC_SERVICESis read once in<clinit>, so theStaticServiceLoadercases need a forked JVM or an isolated class loader.
Related
- micronaut-runner serves its build-time service table through
SoftServiceLoader.Optimizations: https://github.com/alvarosanchez/micronaut-runner/issues/154 (tracked in https://github.com/alvarosanchez/micronaut-runner/issues/109). - #13389 builds on these fixes.
Source: micronaut-projects/micronaut-core