Enums as Singleton Class

Enums are the best candidates for Singleton class in java. Enum doesn't have a constructor, so creation and initialization are handled by JVM internally, hence can't be made public using reflection.

Enum variables declared once, can be accessed globally throughout the application, Enums are internally thread safe. After Java 1.5, enums are considered as the most safest way to create Singleton objects.

Java Enum constants Serialization or Externalization happen differently than normal constant Serialization or Externalization. A Serialized version of the enum contains only its name, the value of the field is not present in the Serialized version.
To Serialize the enum constant ObjectOutputStream takes the same value returned by the enum and at the time of Deserialization ObjectInputStream resolves the name and value from the stream or network.

The enum Serialization and Deserialization process are monitored by JVM and any modification in the methods of Serialisation and Deserialization process like writeObject, readObject, readObjectNoData, writeReplace, and readResolve will be ignored.

all enum types have a fixed serialVersionUID of 0L. In addition to serialPersistentFields or serialVersionUID field declarations will also be ignored.
 

package org.wesome.dsalgo.design.pattern.singleton;

public enum Apple {
    AppleInstance;

    Apple() {
        System.out.println("Apple default constructor");
    }

    public static void favoriteFruitUtilityFunc() {
        System.out.println("Apple is my favorite fruit.");
    }
}
package org.wesome.dsalgo.design.pattern.singleton;

public class SingletonClass {
    public static void main(String[] args) {
        Apple.favoriteFruitUtilityFunc();
        System.out.println(Apple.AppleInstance);
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.4.1"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

Drawbacks of Enum singleton object

  • Enum constants are initialized and loaded in memory at the bootup time, hence it doesn't allow lazy loading.
  • Singleton class might need to extend some class or implement an interface, enums are not allowed to extend or implement.

follow us on