While this is a common approach, it’s important to note that it can be problematic in a multithreading scenarios, which is the main reason for using Singletons.

Simply put, it can result in more than one instance, breaking the pattern’s core principle. Although there are definitely locking solutions for this problem, our next approach solves these problems at a root level.

3. Enum Singleton

Moving forward, let’s not discuss another interesting approach – which is to use enumerations:

This approach has serialization and thread-safety guaranteed by the enum implementation itself, which ensures internally that only the single instance is available, correcting the problems pointed out on the class-based implementation.

4. Usage

In order to use our ClassSingleton, we simply need to get the instance statically: