How to Create Singleton Class in Java?

Declare a private static instance of the class

Make the constructor private

Provide a public static method to return the instance

Initialize the instance eagerly or lazily

Use synchronization if lazy initialization must be thread-safe

Use double-checked locking with `volatile` for better performance

Use an enum singleton for the simplest thread-safe approach

`public class Singleton {`

` private static Singleton instance;`

` private Singleton() {}`

` public static Singleton getInstance() {`

` if (instance == null) {`

` instance = new Singleton();`

` }`

` return instance;`

` }`

`}`

Suggested for You

Trending Today