How to write a singleton?

Singleton is a design pattern that ensures a class has only one instance. This broad definition opens up a variety of implementation approaches, which in turn invites detailed questions that an interviewer might expect.

The first thing to clarify is what is the exact context of the "single instance". In the basic case, the uniqueness of the object is ensured at the class implementation level. However, this basic approach results in one object per class loader. For uniqueness across the entire virtual machine, the implementation needs to be extended. More actions at the OS level might be required to achieve a single instance across JVM processes. Alternatively, a framework-specific "scope of uniqueness" narrowing might be required. For example, one instance per Spring IoC container.

Next, you should find out whether there should be exactly one instance or at most one. Simply put, should its creation be lazy? The lifetime of the object might be limited by external conditions, and it may need to be disposed of later.

Finally, it is important to specify under what circumstances it is intended to be used. Typically, a multi-threaded environment is assumed – instantiation needs to be synchronized. Another possible requirement is the preservation of state from one run to another. The range of options here is limited only by the interviewer's imagination.

There are many articles written about specific implementation options. In interviews, knowledge of the most standard approaches is usually expected.