HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

What is an efficient way to implement a singleton pattern in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
efficientimplementjavawaypatternwhatsingleton

Problem

What is an efficient way to implement a singleton design pattern in Java?

Solution

Use an enum:

public enum Foo {
    INSTANCE;
}


Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}


Edit: An online portion of "Effective Java" says:


"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

Code Snippets

public enum Foo {
    INSTANCE;
}
public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}

Context

Stack Overflow Q#70689, score: 823

Revisions (0)

No revisions yet.