Minborg

Minborg
Minborg
Showing posts with label singleton. Show all posts
Showing posts with label singleton. Show all posts

Monday, October 8, 2018

Java: Gain Performance Using SingletonStream

Java streams with just one element sometimes create unnecessary overhead in your applications. Learn how to use SingletonStream objects and gain over tenfold performance for some of these kinds of streams and learn how, at the same time, you can simplify your code.

Background

The Stream library in Java 8 is one of the most powerful additions to the Java language ever. Once you start to understand its versatility and resulting code readability, your Java code-style will change forever. Instead of bloating your code with all the nitty and gritty details with for, if and switch statements and numerous intermediate variables, you can use a Stream that just contains a description of what to do, and not really how it is done.

Some years ago, we had to make an API decision for a Java project: Which return type should we select for the two fast local in-memory data cache methods with;

  • a unique search key which returns either a value or no value
  • a non-unique search key which returns any number of values (zero to infinity). 


This was the initial idea:

Optional<T> searchUnique(K key); // For unique keys
Stream<T> search(K key);         // For non-unique keys

But, we would rather have the two methods look exactly the same and both return a Stream<T>. The API would then look much cleaner because a unique cache would then look exactly the same as a non-unique cache.

However, the unique search had to be very efficient and able to create millions of result objects each second without creating too much overhead.

The Solution

By implementing a SingletonStream that only takes a single element (and therefore can be highly optimized compared to a normal Stream with any number of elements), we were able to let both methods return a Stream while retaining performance. The method searchUnique(K key) would return an empty stream (Stream.empty()) if the key was not found, and it would return a SingletonStream with the value associated with the key if the key existed. We would get:

Stream<T> searchUnique(K key); // For unique keys
Stream<T> search(K key);       // For non-unique keys

Great! We can eat the cookie and still have it!

The Implementation

The SingletonStream is a part of the Speedment Stream ORM and can be viewed here on GitHub.  Feel free to use Speedment and any of it's component in your own projects using the Speedment initializer.

The SingletonStream is a good candidate for stack allocation using the JVM's Escape Analysis (read more on Escape Analysis in my previous posts here and here). The implementation comes in two shapes. if we set the STRICT value to true, we will get a completely lazy Stream, but the drawback is that we will lose the Singleton Property once we call some Intermediate Operations like .filter(), map() etc. If we, on the other hand, set the STRICT value to false, the SingletonStream will perform many of the Intermediate Operations eagerly and it will be able to return a new SingletonStream thereby retaining the Singleton Property. This will give better performance in many cases.

The solution devised here for reference streams could also easily be modified to the primitive incarnations of singleton streams. So, it would be almost trivial to write a SingletonIntStream, a SingletonLongStream and a SingletonDoubleStream. Here is a SingletonLongStream.

It should be noted that the class could be further developed so it could support lazy evaluation while still being always high performant. This is a future work.

Performance

There are many ways one could test the performance of the SingletonStream and compare it with a standard Stream implementation with one element.

Here is one way of doing it using JMH. The first tests (count) just counts the number of elements in the stream and the second tests (forEach) does something with one element of a stream.

@Benchmark
public long singletonStreamCount() {
    return SingletonStream.of("A").count();
}

@Benchmark
public long streamCount() {
    return Stream.of("A").count();
}

@Benchmark
public void singletonStreamForEach() {
    SingletonStream.of("A")
        .limit(1)
        .forEach(blackHole());
}

@Benchmark
public void streamForEach() {
   Stream.of("A")
        .limit(1)
        .forEach(blackHole());
}

private static <T> Consumer<T> blackHole() {
    return t -> {};
}


This will produce the following result when run on my MacBook Pro laptop:
...
Benchmark                               Mode  Cnt           Score   Error  Units
SingletonBench.singletonStreamCount    thrpt        333419753.335          ops/s
SingletonBench.singletonStreamForEach  thrpt       2312262034.214          ops/s
SingletonBench.streamCount             thrpt         27453782.595          ops/s
SingletonBench.streamForEach           thrpt         26156364.956          ops/s
...

That's a speedup factor over 10 for the "count" operation. For the "forEach" operation, it looks like the JVM was able to completely optimize away the complete code path for the SingletonStream.

Test It

Download Speedment using the Speedment initializer.

The complete test class is available here.

Conclusions

The SingletonStream works more or less as an extended Optional and allows high performance while retaining the benefits of the Stream library.

You can select two versions of it by setting the STRICT value to your preferred stringency/performance choice.

The SingletonStream could be further improved.

Wednesday, February 3, 2016

Plugin Your Own Components with Java 8

Components are Good!


Spire and Duke is plugging in...
A couple of years ago when I worked in the telecom industry, I spent time cleaning up Java code that mixed the concept of abstraction (interfaces) and implementation (concrete classes implementing one or several interfaces).

Another related problem I have come across several times, is the use of Singletons, used to hold various implementations. To be fair, I have created more than a couple of those singletons myself, but nowadays, I almost never use them.

In this post, I will show why and how to avoid them and at the same time gain some additional advantages like separation of interfaces and implementations using Components and a ComponentHandler.

The ComponentHandler that is shown in the examples a bit further down is derived from the open-source project Speedment that I am contributing to. Speedment is great if you want to write database applications in Java 8 using standard Java 8 Streams. Read more about Speedment here.

Why Are Singletons Bad?

The purpose of a singleton is to guarantee that just a single instance of a class or interface is present at any single time. This is of course not a bad thing in it self. On the contrary, there are many situations when we want this property, for example for logging or for other system components like queues or factories. However, the way people chose to enforce the singleton property is more often than not, simply bad.

In my previous post Enforcing Java Singletons is Very Hard, I presented a number of Singleton Idioms that can be used to enforce the singleton property and in the same post, I showed that it is hard to really enforce the singleton patterns (albeit "cheating" with reflections) and also talked about some other disadvantages of singletons.

Here is one of the idioms from the post, called the Enum Singleton Idiom which I first learned about in Joshua Bloch's book "Effective Java" many years ago.

public enum FooEnumSingleton {

    INSTANCE;

    public static FooEnumSingleton getInstance() { return INSTANCE; }

    public void bar() { }

}

This provides a relatively solid and simple singleton, but there are some drawbacks. Because all enums inherit from the built-in Java class Enum, we can not inherit from other base classes. Furthermore, we can not override methods when we want to test our singleton in JUnit tests, for example if we want to "harnes" our class, call some methods and then inspect its state or functionality. Additionally, there is no support or control over the singletons Lifecycle Management. When we first reference the singleton above, the class loader will create and initialize it, pretty much outside our control. If another programmer calls our singleton, it will load no matter what. Now, if our singleton depends on other singletons, which each depends on yet another singleton and so on, our code will likely break. Perhaps not in the first version where things were easy, but it is just a matter of time until it undoubtedly will fail.

I will talk more about lifecycles in the next section.

Component Lifecycles

The Lifecycle of a component or class can be certain stages the component will pass during the time it exists. For example, a component may be created, added, started, stopped and and then eventually, removed from a system. Using the right tools, a component can easily be setup to react to its own lifecycle events.

The Component Handler

Often, it is very convenient to setup some kind of Component Handler that keeps track of all our singleton components. This way, we can have them all collected at one place and treat them in a consistent way. The Component Handler can also be made to automatically call the component's lifecycle methods whenever they are added, changed or removed from the Component Handler.

Now, do not fall for the temptation to make the Component Handler a singleton under the excuse that "now it is just one singleton". Admittedly, it is better to have just one singleton than having 100 singletons, but it is generally even better to just let our Component Handler be just a normal object and keep track of the Component Handler instance in our code. Especially if we are deploying our application in a web server, where there might be many instances of the "Singletons" under different class loaders.

The Class Mapper

The classical (apologies for the bad word-joke) "Class Mapper" is a good starting point when we want to implement a Component Handler. Take a look at this example:

public interface ClassMapper {

    /**
     * Puts a new mapping and returns the previous mapping for the given class,
     * or null if no mapping existed.
     *
     * @param <K> key class
     * @param <V> item type
     * @param keyClass to use
     * @param item to add
     * @return the previous mapping that existed, or null 
     *         if no mapping existed
     */
    <K, V extends K> K put(Class<K> keyClass, V item);

    /**
     * Returns the mapping for the given class, or null if no mapping exists
     *
     * @param <K> The class type
     * @param clazz the class to use
     * @return the mapping for the given class, or null if no mapping exists
     */
    public <K> K get(Class<K> clazz);

}

and a corresponding (almost trivial) implementation:

public class ClassMapperImpl implements ClassMapper {

    private final Map<Class<?>, Object> map;

    public ClassMapperImpl() {
        this.map = new ConcurrentHashMap<>();
    }

    @Override
    public <K, V extends K> K put(Class<K> keyClass, V item) {
        requireNonNull(keyClass);
        requireNonNull(item);
        @SuppressWarnings("unchecked")
        // We know that it is a safe cast
        // because V extends K
        final K result = (K) map.put(keyClass, item);
        return result;
    }

    @Override
    public <K> K get(Class<K> clazz) {
        @SuppressWarnings("unchecked")
        // We know that it is a safe cast
        // because the previous put()
        // guarantees this
        final K result = (K) map.get(clazz);
        return result;
    }

}

The good thing with this is that now we have a small rudimentary Component Handler. Suppose that we have an interface like this:

public interface JokeComponent {

    String nextJoke();

}
The nextJoke() method is supposed to return a funny joke, and we want a pluggable concept so we are planning to implement several versions of the JokeComponent. We start by constructing a very simple JokeComponent that just returns a single joke regardless how many times we call the nextJoke() method:

public class StaticJokeComponent implements JokeComponent {

    @Override
    public String nextJoke() {
        return "I went to buy some camouflage trousers the other day,"
                + " but I couldn’t find any.";
    }

}
Now we can test our Component Handler as shown in the following program:

public class Main {

    public static void main(String[] args) {
        final ClassMapper componentHandler = new ClassMapperImpl();
        setupComponents(componentHandler);

        crankOutTenJokes(componentHandler);
    }

    private static void setupComponents(ClassMapper componentHandler) {
        // Plug in the selected basic JokeGenerator
        componentHandler.put(JokeComponent.class, new StaticJokeComponent());
    }

    private static void crankOutTenJokes(ClassMapper componentHandler) {
        // Get the current JokeGenerator that is plugged into the componentHandler
        JokeComponent jokeGenerator = componentHandler.get(JokeComponent.class);
        // Tell the world who is making the jokes
        System.out.println(jokeGenerator.getClass().getSimpleName() + " says:");
        // print ten of its joke
        IntStream.rangeClosed(1, 10)
                .mapToObj(i -> jokeGenerator.nextJoke())
                .forEach(System.out::println);
    }

}

This will produce the following jokes:

StaticJokeComponent says:
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
I went to buy some camouflage trousers the other day, but I couldn’t find any.
Even though the joke might be a bit fun the first or second time, we start to lose interest a bit further down the list... Time for improvement by writing a new JokeComponent that doesn't tell the same joke all the time.

public class RandomJokeComponent implements JokeComponent {

    private final Random random = new Random();
    private final List<String> jokes = Arrays.asList(
            "What's blue and doesn't weigh much? Light blue.",
            "What do you get when you cross a joke with a rhetorical question?",
            "What do you call a fish with no eyes? A fsh.",
            "Two men walk into a bar... the third one ducks.",
            "A farmer rounded up her 196 cows and got 200 of them."
    );

    @Override
    public String nextJoke() {
        return jokes.get(random.nextInt(jokes.size()));
    }

}
Now we can plug in this JokeComponent instead and see what happens. Modify the code so it looks like this instead:

    private static void setupComponents(ClassMapper componentHandler) {
        // Plug in the selected basic JokeGenerator
        // Use the RandomJokeGenerator this time instead ---+
        //                                                  V
        componentHandler.put(JokeComponent.class, new RandomJokeComponent());
    }
Now we get another output:
What's blue and doesn't weigh much? Light blue.
Two men walk into a bar... the third one ducks.
A farmer rounded up her 196 cows and got 200 of them.
What do you call a fish with no eyes? A fsh.
What do you get when you cross a joke with a rhetorical question?
A farmer rounded up her 196 cows and got 200 of them.
What do you get when you cross a joke with a rhetorical question?
What do you call a fish with no eyes? A fsh.
What's blue and doesn't weigh much? Light blue.
What do you call a fish with no eyes? A fsh.
This is a small step forward for the humor society, but we could as well write yet another implementation of the JokeComponent that, whenever nextJoke() is called, goes out on the internet and retrieves a funny story from some site. The user code outside the component would remain exactly the same.

Note that the Component Handler can handle any number of interfaces and the interfaces can look completely different and contain different methods, so you could set it up to also handle RidleComponent and perhaps also BlooperComponent that could, for instance, return URL:s to funny films on the net.

The ComponentHandler with Lifecycles


It is fairly easy to expand the Component Handler so it can handle Component Lifecycles. Let us define a simple Lifecycle Component like this.

public interface Component {

    void added();

    void removed();
}
So, every time we add a Component to the Component Handler, we want the Component Handler to automatically invoke the Component::add method and every time it is removed we want it to call the Component::removed method. That way, we know that all component in the Component Handler will be initialized (by the added() method) properly and also that they will clean up stuff (if needed by the removed() method) when they are removed from the Component Handler. Evidently, every component that we want to add to the Component Handler must implement the Component interface. First, we improve the ClassMapper interface so it takes a generic parameter for the values to extend.

public interface ClassMapper<T> {

    <K extends T, V extends K> K put(Class<K> keyClass, V item);

    public <K extends T> K get(Class<K> clazz);

}

Then we could write a ComponentHandler as depicted here under:

public class ComponentHandler implements ClassMapper<Component> {

    private final Map<Class<? extends Component>, Component> map;

    public ComponentHandler() {
        this.map = new ConcurrentHashMap<>();
    }

    @Override
    public <K extends Component, V extends K> K put(Class<K> keyClass, V item) {
        requireNonNull(keyClass);
        requireNonNull(item);
        item.added();
        @SuppressWarnings("unchecked")
        // We know that it is a safe cast
        // because V extends K
        final K result = (K) map.put(keyClass, item);
        if (result != null) {
            result.removed();
        }
        return result;
    }

    @Override
    public <K extends Component> K get(Class<K> clazz) {
        @SuppressWarnings("unchecked")
        // We know that it is a safe cast
        // because the previous put()
        // guarantees this
        final K result = (K) map.get(clazz);
        return result;
    }

}

I have made some simplifications in the code, but the general outline becomes obvious. Whenever we add a Component, its added() method will be called and whenever we replace a component with a new one, the old's removed() method is called.

In the example below, we are to make a Queue for Strings that is a pluggable Component in the new ComponentHandler we just wrote. We could define a StringQueueComponent as a Component like this:

public interface StringQueueComponent extends Component {

    boolean offer(String msg);

    String poll();
}
We could start with a very straightforward implementation using one of the existing Queue implementation already in the Java framework.

public class MemoryStringQueueComponent implements StringQueueComponent {

    private final Queue<String> queue = new ConcurrentLinkedQueue<>();

    @Override
    public boolean offer(String msg) {
        return queue.offer(msg);
    }

    @Override
    public String poll() {
        return queue.poll();
    }

    @Override
    public void added() {
        System.out.println(getClass().getSimpleName() + " added");
    }

    @Override
    public void removed() {
        queue.clear();
        System.out.println(getClass().getSimpleName() + " removed");
    }

}
and then we may come up with an alternative Queue that places the strings on a file as shown in this outline (I have not shown the actual code for file handling because it is quit bulky, but the principle is obvious).

public class FileStringQueueComponent implements StringQueueComponent {

    // File variable goes here

    @Override
    public boolean offer(String msg) {
        // Append the string to the file
    }

    @Override
    public String poll() {
        // Check if the file has grown
        // if yes, read the next line and return it
        // if no, return null
    }

    @Override
    public void added() {
        // Open the file and trunkate it if contains an old queue.
        // Set a pointer to the current file location
    }

    @Override
    public void removed() {
        // Close the file and remove it from the file system
    }

}
So now, when we put the new ComponentHandler to use as depicted below:

public class Main {

    public static void main(String[] args) {
        ComponentHandler componentHandler = new ComponentHandler();
        setupComponents(componentHandler);
        ///
        putStuffInTheStingQueue(componentHandler);
        printStuffInTheStringQueue(componentHandler);

        // Select a new queue component (content of the old queue is lost)
        componentHandler.put(StringQueueComponent.class, new FileStringQueueComponent());

        putStuffInTheStingQueue(componentHandler);
        printStuffInTheStringQueue(componentHandler);

    }

    private static void putStuffInTheStingQueue(ComponentHandler componentHandler) {
        StringQueueComponent queue = componentHandler.get(StringQueueComponent.class);
        queue.offer("A");
        queue.offer("B");
        queue.offer("C");
    }

    private static void printStuffInTheStringQueue(ComponentHandler componentHandler) {
        StringQueueComponent queue = componentHandler.get(StringQueueComponent.class);
        System.out.println("Stuff in " + queue.getClass().getSimpleName());
        String s;
        while ((s = queue.poll()) != null) {
            System.out.println(s);
        }
    }

    private static void setupComponents(ComponentHandler componentHandler) {
        componentHandler.put(StringQueueComponent.class, new MemoryStringQueueComponent());
    }

}
it will produce the following output (given a real implementation of the FileStringQueueComponent):

MemoryStringQueueComponent added
Stuff in MemoryStringQueueComponent
A
B
C
FileStringQueueComponent added
MemoryStringQueueComponent removed
Stuff in FileStringQueueComponent
A
B
C

Conclusion


By using a Component Framework, we gain many advantages over singletons :

  • We can control the lifecycle of our components.
  • The ability to test our components becomes much better.
  • We get a clear separation between interfaces an implementations.
  • We collect all our component in one place and access them in a standardized way.
  • We can ensure that our component is not called before it is initialized.
  • Our code will be less likely to fail in a multi-classloader scenario like a web server.


If you want to take a look at a real existing component handler, have a look at Speedment's  component handler on GitHub. For performance reasons, this component handler is more optimized so that we can obtain components without the overhead of looking them up in a Map.


Saturday, January 31, 2015

Enforcing Java Singletons is Very Hard

Background

A singleton is a class that is instantiated exactly one time and can be used to represent "global" or system wide components. Common usages of singletons include loggers, factories, window managers or platform components. My general tip is to avoid using singletons when possible, because it is difficult to break out or override functionality and also to write test mocks and they also tend to create a bad over all code structure. As it turns out in this post, they are also insecure.

Many efforts has been made to devise good singleton patterns but there is one surprisingly easy and efficient way of doing it. However, there is really no rock solid way of guaranteeing that the singleton integrity is not breached. Read this post and see if you agree.

The Final Field Scheme

This solution relies on keeping the constructor private and exporting a public static final member to provide singleton access like this:

public class FooSingleton {

    public final static FooSingleton INSTANCE = new FooSingleton();

    private FooSingleton() { }
   
    public void bar() { }
       
}

When the class is first referenced, the static members are initialized whereby the private constructor is called only once. It is guaranteed that, even though several threads may reference the class before it has been initialized, the JVM will make sure that the class is properly initialized before the threads can continue to run. However, there is a risk that someone might create spurious instance of the class using reflection, using the setAccessible(true) method. This is how it can be done:

Constructor[] constructors = FooSingleton.class.getDeclaredConstructors();
Constructor constructor = constructors[0];
constructor.setAccessible(true);
FooSingleton spuriousFoo = (FooSingleton) constructor.newInstance(new Object[0]);
We need to modify the constructor so it protects the class from being constructed multiple times, for example by throwing an exception when it is called again. If we modify the FooSingleton like this, we protect against such attacks:

public class FooSingleton2 {

    private static boolean INSTANCE_CREATED;
    public final static FooSingleton2 INSTANCE = new FooSingleton2();

    private FooSingleton2() {
        if (INSTANCE_CREATED) {
            throw new IllegalStateException("You must only create one instance of this class");
        } else {
            INSTANCE_CREATED = true;
        }
    }

    public void bar() { }

}

Although this appears much safer, is it almost as easy as before to create undesired instances of the class. We can just pick up the INSTANCE_CREATED field and modify it before we do the same trick as before like demonstrated here under:

Field f = FooSingleton2.class.getDeclaredField("INSTANCE_CREATED");
f.setAccessible(true);
f.set(null, false);

Constructor[] constructors = FooSingleton2.class.getDeclaredConstructors();
Constructor constructor = constructors[0];
constructor.setAccessible(true);
FooSingleton2 spuriousFoo = (FooSingleton2) constructor.newInstance(new Object[0]);

This is not a viable solution because any protection we introduce may be circumvented using reflection.

The Static Factory Scheme

In this approach, the public member is a static factory like this:

public class FooSingleton3 {

    public final static FooSingleton3 INSTANCE = new FooSingleton3();

    private FooSingleton3() { }

    public static FooSingleton3 getInstance() { return INSTANCE; }

    public void bar() { }

}

When getInstance() is called, it always returns the same object reference. Even though this scheme has the same reflection vulnerability as the previous scheme, it has some advantages. For example, you can change the enforcement of the singleton without changing your actual API as you will see later in this post. Historically, a getInstance() method has been used for most singleton implementations and, by de-facto convention, it constitutes a clear marker that this really is a singleton.

The Initialization-on-demand Holder Idiom

If you want to defer the creation of the singleton as much as possible (i.e. lazy initialization), you can use the Initialization-on-demand Holder Idiom where the singleton is created in a thread safe way when the getInstance() is first called. This is an improvement over the previous schemes where the singleton is created when the class is first referenced (i.e. eager initialization). It looks like this:

public class FooSingleton4 {
  
    private FooSingleton4() {
    }
  
    public static FooSingleton4 getInstance() {
        return FooSingleton4Holder.INSTANCE;
    }
  
    private static class FooSingleton4Holder {

        private static final FooSingleton4 INSTANCE = new FooSingleton4();
    }
}

Look Out for Serializable

If the singleton implements serializable, it is exposed to another threat to its singleton property. Because of this, you need to declare all fields transient (so that they are not serialized) and provide a custom readResolve() method that just returns the INSTANCE reference.

The Enum Idiom

This scheme simply uses an Enum as the holder of the single INSTANCE member like this:

public enum FooEnumSingleton {

    INSTANCE;

    public static FooEnumSingleton getInstance() { return INSTANCE; }

    public void bar() { }

}

According to the Java Language Specification §8.9 "The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants."

Thus, we allegedly get protection against serialization, clone and reflection attacks for free. When I first saw this statement, I immediately felt compelled to prove it wrong. As you can see in the following code snippet, it was fairly easy to get around the protection.

 Constructor con = FooEnumSingleton.class.getDeclaredConstructors()[0];
 Method[] methods = con.getClass().getDeclaredMethods();
 for (Method method : methods) {
     if (method.getName().equals("acquireConstructorAccessor")) {
         method.setAccessible(true);
         method.invoke(con, new Object[0]);
     }
  }
  Field[] fields = con.getClass().getDeclaredFields();
  Object ca = null;
  for (Field field : fields) {
      if (field.getName().equals("constructorAccessor")) {
          field.setAccessible(true);
          ca = field.get(con);
      }
  }
  Method method = ca.getClass().getMethod("newInstance", new Class[]{Object[].class});
  method.setAccessible(true);
  FooEnumSingleton spuriousEnum = (FooEnumSingleton) method.invoke(ca, new Object[]{new Object[]{"SPURIOUS_INSTANCE", 1}});
  printInfo(FooEnumSingleton.INSTANCE);
  printInfo(spuriousEnum);
}

private static void printInfo(FooEnumSingleton e) {
    System.out.println(e.getClass() + ":" + e.name() + ":" + e.ordinal());
}
When we run the code, we get the following output:
class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:INSTANCE:0
class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:SPURIOUS_INSTANCE:1

A disadvantage with the Enum scheme is that we can not inherit from another base class, because enums can not extend another class. The reason for that is that it already inherently extends java.lang.Enum. If you want to mimic inheritance, you might want to consider the interface mixin pattern as described in my previous post here.

An advantage with the enum scheme is that, if you later decide to have "dualtons" or "tringletons", it is very easy to add those just by adding new enums. For example, if you have a singleton cache, you might later decide to introduce several layers of the cache.

Conclusions

All though it is difficult to circumvent some of the singleton property protections shown here, there is no really bullet prof singleton scheme around. If you can think of a better one, please feel free to drop a comment on this post!

An Enum provides a good and simple vehicle for singletons. The Initialization-on-demand holder idiom provides a good pattern if you want to use inheritance and/or want lazy initialization.

Good luck with your singletons!