Java – Are there penalties for Enum Singletons


Are there (performance) penalties* associated with the Enum Singleton Pattern in any way, as it seems to be used less than the classical singleton pattern or the inner holder class idiom?

* Penalties, such as the cost of serializability in cases when it is not needed and such, or is the usage low because few of the developers read Effective Java 2nd edition?

Best Solution

All Java singleton patterns (both this and the standard with private constructor and static accessor) have this bad property that if you to test them (or test anything that even remotely depends on them) can use this and only this object.

For example if you want to test PrintingService class that depends on PrintingSingleton you will not be able to replace this printing singleton with a mock because it is bound statically.

i.e. imagine testing this function

boolean printDocument(Document d) {
  if (PrintingSingleton.INSTANCE.isPrinterEnabled()) {
  throw new RuntimeExeption("Printing not enabled");

with a test

@Test(expectedExceptions = {RuntimeException.class})
public void testPrinting() {
  PrintingService service = ...
  service.print(new Document());  // How will you simulate 
                                  // throwing an exception?

Personally, I would just avoid using singletons that way but rather introduce dependency injection, via Guice, Spring or Pico Container. That way you ensure existence of only one object, while not limiting yourself to not being able to mock the object out for example for tests.