Java

Singleton via enum

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`enum` with a single value is the simplest correct singleton implementation: lazy, thread-safe, serialization-safe, reflection-safe. Joshua Bloch's recommendation in Effective Java.
Java
Raw
public enum Config {
    INSTANCE;

    private final Properties props = new Properties();

    Config() {
        // Constructor is called exactly once, by the JVM
        try (var in = ClassLoader.getSystemResourceAsStream("config.properties")) {
            if (in != null) props.load(in);
        } catch (IOException e) {
            throw new RuntimeException("failed to load config", e);
        }
    }

    public String get(String key) { return props.getProperty(key); }
    public int getInt(String key, int def) {
        var v = props.getProperty(key);
        return v == null ? def : Integer.parseInt(v);
    }
}

// Usage from anywhere
class App {
    public static void main(String[] args) {
        var dbUrl = Config.INSTANCE.get("db.url");
        var port  = Config.INSTANCE.getInt("server.port", 8080);
        System.out.println(dbUrl + " : " + port);
    }
}

// Why enum is the best singleton:
//   - Lazy initialization: enum constants are constructed on first reference
//   - Thread-safe: JVM enforces this for enum class initialization
//   - Serialization-safe: enum constants survive serialization round-trip
//   - Reflection-safe: cannot use newInstance() to create another
import java.io.IOException;
import java.util.Properties;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.