Skip to content
Home » How to Create a Lazily Initialized Singleton in Java

How to Create a Lazily Initialized Singleton in Java

white and tan english bulldog lying on black rug

Here’s how to create a lazily initialized singleton in Java.

import java.time.LocalDateTime;

public final class MySingletonClass {

    private final LocalDateTime creationDateTime;

    private MySingletonClass(LocalDateTime creationDateTime) {
        this.creationDateTime = creationDateTime;
    }

    public LocalDateTime getCreationDateTime() {
        return creationDateTime;
    }

    public static MySingletonClass getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private static final class InstanceHolder {
        static final MySingletonClass INSTANCE = new MySingletonClass(LocalDateTime.now());
    }
}

If you have any questions, leave a comment or ask me on my social media.