Service loading: skip ImageSingletons lookup on the JVM and apply name condition on all paths

Author: alvarosanchezCreated Sep 24, 2026Updated Sep 24, 2026
Labelstype: bugrelates-to: graal

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

  1. Service loading on the JVM does not throw and catch an error on every scan. Outside image code, ImageSingletons.contains(..) is always false: nativeimage 25.3.4.1 checks ImageInfo.inImageCode(), which reads the same org.graalvm.nativeimage.imagecode property as NativeImageUtils. Skipping the lookup therefore changes no result.
  2. 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 native ImageSingletons table and a registered StaticServiceLoader.

Actual Behaviour

1. Every service scan on the JVM throws a NoClassDefFoundError.

  • ServiceScanner.findStaticServiceDefinitions() calls NativeImageUtils.hasImageSingletons(), which evaluates ImageSingletons.class inside catch (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 new NoClassDefFoundError.
  • The lookup runs twice per META-INF/services scan (the ServiceEntriesLoader constructor, then findMicronautMetaServiceEntries from compute) and once per META-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.JavaErrorThrow is on in default.jfc.

2. Three of the four paths drop the name condition.

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

  1. Start any Micronaut app on a JVM without the GraalVM SDK, with -Xlog:exceptions=info, and grep the output for ImageSingletons.
  2. On the JVM, SoftServiceLoader.load(BeanDefinitionReference.class, cl, n -> false).collectAll() still returns every reference (2d).
  3. With a SoftServiceLoader.Optimizations registered, collectAll() and iterator() 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=info showed 22–28 NoClassDefFoundErrors plus one ClassNotFoundException per 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 to NativeImageUtils and added the Crema escape hatch; the JVM path is unchanged.

Example Application

https://github.com/alvarosanchez/micronaut-runner/tree/5fb62e39cadfee8f087e3f3b0a0d6be424885b39/test-suite/samples/benchmark-large

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

  1. 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 final cache: io.micronaut.core.io and io.micronaut.core.util are initialised at build time, so a cache would hold the image builder's value.
  2. 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, and load(predicate) otherwise. That way an implementation overriding only load(Predicate<S>) does not silently fall back to the sequential default.
    • Treat a null lineCondition as accept-all, because SoftServiceLoaderTest passes null.
  3. Document StaticServiceLoader: the default load is sequential, JIT implementations should fork one task per entry and join in order, and isPresent() is always true. Leave the public default unchanged.
Sketch
diff
--- 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/micronaut entries when a caller passes a condition. That follows the documented contract, but it deserves a release note.

Tests

  • With org.graalvm.nativeimage.imagecode unset, findStaticServiceDefinitions() returns null, and a jdk.JavaErrorThrow recording around collectAll() shows no ImageSingletons error. imageSingletonsLookupCanBeDisabled keeps passing.
  • A condition that rejects one entry, tested for collectAll, iterator() and META-INF/micronaut entries. STATIC_SERVICES is read once in <clinit>, so the StaticServiceLoader cases need a forked JVM or an isolated class loader.

Related

Source: micronaut-projects/micronaut-core