Fundamentals 4 min read

Implementing the Singleton Pattern in Java: Enum and Static Inner Class Approaches

This article explains how to implement the Singleton pattern in Java using both an enum‑based approach and a static inner‑class technique, providing thread‑safe examples from Spring Data JDBC and MyBatis along with Maven dependency snippets and detailed code illustrations.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Implementing the Singleton Pattern in Java: Enum and Static Inner Class Approaches

The Singleton pattern ensures that a class has only one instance and provides a global access point. In Java, two common thread‑safe implementations are using an enum and using a private static inner class.

Enum‑based Singleton

Enum instances are inherently thread‑safe because the JVM guarantees that enum values are instantiated only once.

public enum JdbcColumnTypes {
  INSTANCE {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Class<?> resolvePrimitiveType(Class<?> type) {
      return javaToDbType.entrySet().stream()
          .filter(e -> e.getKey().isAssignableFrom(type))
          .map(e -> (Class<?>) e.getValue())
          .findFirst()
          .orElseGet(() -> (Class) ClassUtils.resolvePrimitiveIfNecessary(type));
    }
  };
  private static final Map<Class<?>, Class<?>> javaToDbType = new LinkedHashMap<>();
  static {
    javaToDbType.put(Enum.class, String.class);
    javaToDbType.put(ZonedDateTime.class, String.class);
    javaToDbType.put(OffsetDateTime.class, OffsetDateTime.class);
    javaToDbType.put(LocalDateTime.class, LocalDateTime.class);
    javaToDbType.put(Temporal.class, Timestamp.class);
  }
  public abstract Class<?> resolvePrimitiveType(Class<?> type);
}

The above code comes from the spring-data-jdbc library. To include it, add the following Maven dependency:

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-jdbc</artifactId>
  <version>2.3.4</version>
</dependency>

Enums can also be used simply to define a set of constants, as shown in the standard AccessMode example from the JDK.

Static Inner Class Singleton

This technique relies on the JVM’s class‑loading guarantees: the inner class is not loaded until it is referenced, and its static fields are initialized in a thread‑safe manner.

public abstract class VFS {
  /** Singleton instance holder. */
  private static class VFSHolder {
    static final VFS INSTANCE = createVFS();

    static VFS createVFS() {
      // ... implementation details ...
    }
  }

  /** Get the singleton VFS instance. If no VFS implementation can be found for the current environment, this method returns null.
   * @return single instance of VFS
   */
  public static VFS getInstance() {
    return VFSHolder.INSTANCE;
  }
}

This snippet is taken from the MyBatis project. Include it with the following Maven dependency:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.9</version>
</dependency>

Key characteristics of the static‑inner‑class approach:

The inner class is lazily loaded, and the JVM guarantees its loading and instantiation are thread‑safe.

The singleton’s constructor is private.

The inner class itself is a private static class.

The inner class holds a static INSTANCE field that creates the singleton instance.

The outer class provides a public static getInstance() method that returns the INSTANCE.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpringMyBatisDesign PatternSingletonstatic inner class
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.