Skip to content

SingletonSupplier is not singleton if null is returned on first supplier call #35369

@mhalbritter

Description

@mhalbritter

When null is returned from the supplier passed to SingletonSupplier and some non-null value on subsequent calls, it breaks the singleton nature.

It returns on first call of singletonSupplier.get() null and then afterwards Hello.

private static int call = 0;

public static void main(String[] args) {
    SingletonSupplier<String> singletonSupplier = SingletonSupplier.ofNullable(() -> supply());
    System.out.println(singletonSupplier.get());
    System.out.println(singletonSupplier.get());
    System.out.println(singletonSupplier.get());
    System.out.println(singletonSupplier.get());
}

private static String supply() {
    call++;
    if (call % 2 == 1) {
        return null;
    }
    return "Hello";
}

prints

null
Hello
Hello
Hello

In Framework 7 it has this signature:

public static <T> @Nullable SingletonSupplier<T> ofNullable(@Nullable Supplier<@Nullable T> supplier) {

suggesting that using a Supplier<@Nullable String> is fine.

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: supersededAn issue that has been superseded by anothertype: bugA general bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions