Top Description Constructors Methods
org.graalvm.nativeimage

public final Class ImageSingletons

extends Object
Class Inheritance
Imports
org.graalvm.nativeimage.hosted.Feature, org.graalvm.nativeimage.impl.ImageSingletonsSupport

A key-value store of singleton objects. The registry is populated during native image generation (no changes are allowed at run time); it is queried both during native image generation and at run time. The key is a class or interface, the value is an instance that extends that class.

When accessing the registry at run time, the key must be a compile time constant. The lookup is performed during native image generation, and the resulting value is put into the compiled code as a literal constant. Therefore, the actual map that stores the key-value data is not necessary at run time, and there is no lookup overhead at run time.

ImageSingletons avoids static fields: instead of filling a static field during native image generation and accessing it at run time, the value is put into the ImageSingletons. Usually, that happens in one of the early initialization methods of a Feature.

Since
19.0

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static <T> void
add(Class<T> key, T value)

Add a singleton to the registry.

public static boolean
contains(Class<?> key)

Checks if a singleton is in the registry.

public static <T> T
lookup(Class<T> key)

Lookup a singleton in the registry.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

ImageSingletonsback to summary
private ImageSingletons()

Method Detail

addback to summary
public static <T> void add(Class<T> key, T value)

Add a singleton to the registry. The key must be unique, i.e., no value must have been registered with the given class before.

Annotations
@Platforms:HOSTED_ONLY
Since
19.0
containsback to summary
public static boolean contains(Class<?> key)

Checks if a singleton is in the registry. The key must be a compile time constant, so that the call to this method can be replaced with the constant true or false.

The method returns false since 19.3.0 when not used in the context of a native image. As such it is safe to write:

if (ImageSingletons.contains(MyService.class)) {
    MyService myService = ImageSingletons.lookup(MyService.class);
    myService.useMyService();
}
and let such code run fine in the context of native image as well as outside of it.
Since
19.0
lookupback to summary
public static <T> T lookup(Class<T> key)

Lookup a singleton in the registry. The key must be a compile time constant, so that the call to this method can be replaced with the constant configuration objects.

The key must have been added before, i.e., the result is guaranteed to be non- null.

Since
19.0