Fundamentals 9 min read

Introduction to the Singleton Design Pattern

The Singleton pattern ensures a class has only one instance, providing a global point of access, and is explained with its definition, implementation steps, advantages, disadvantages, thread‑safety concerns, usage guidelines, and typical real‑world scenarios such as configuration management, logging, and resource pooling.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Introduction to the Singleton Design Pattern

Click the above “Java Interview Questions” to follow the public account.

Singleton Pattern Introduction:

The Singleton pattern, also known as the single instance pattern, is a common software design pattern that ensures a class has only one instance, which is useful when a system needs a global object to coordinate overall behavior.

For example, in a server program, configuration data stored in a file can be read by a singleton object, and other components obtain the configuration through this singleton, simplifying configuration management in complex environments.

Implementation Idea of Singleton Pattern:

A class provides a static method (commonly named getInstance) that returns the same object reference each time.

The method checks whether the stored reference is null; if not, it returns the existing instance, otherwise it creates a new instance and stores the reference.

The class constructor is declared private so that objects cannot be instantiated directly; only the static method can obtain the unique instance.

Points to Note:

In multithreaded environments, the singleton must be used carefully. If two threads simultaneously invoke the creation method before the unique instance exists, both may create separate instances, violating the singleton principle.

The solution is to protect the instance‑checking variable with a mutex lock, although this may reduce efficiency.

Advantages:

Only one active instance exists, preventing other objects from creating additional instances and ensuring all access the same object.

The pattern offers some scalability, as the class controls its own instantiation process.

Provides controlled access to the unique instance.

Since only one object resides in memory, it saves system resources and can improve performance for frequently created and destroyed objects.

Allows a variable number of instances (when needed).

Avoids multiple occupancies of shared resources.

Disadvantages:

Not suitable for objects that need to vary across use cases; a singleton can cause data errors and cannot preserve independent states.

Because there is no abstraction layer, extending a singleton class is difficult.

The singleton class often has too many responsibilities, violating the Single Responsibility Principle.

Misuse can lead to problems such as resource contention (e.g., making a database connection pool a singleton may cause overflow) or loss of state when an idle instance is garbage‑collected.

Usage Precautions:

Do not create a singleton via reflection, as this can instantiate a new object.

When using lazy initialization, be aware of thread‑safety issues.

Both eager and lazy singleton constructors are private and cannot be inherited; some singleton variants (e.g., registration‑based) can be inherited.

Applicable Scenarios:

The singleton pattern saves memory and speeds up object access, making it suitable when an object must be shared across multiple modules, such as a frequently used data source connection.

Objects that are instantiated and destroyed frequently. Objects whose creation is costly in time or resources but are needed often. Stateful utility objects, e.g., those that frequently access databases or files.

Typical classic use cases include:

Resource sharing to avoid performance loss, such as logging files or application configuration.

Controlling resources to facilitate communication between them, such as thread pools.

Application Scenarios:

1. External resources: a printer spooler where only one instance should manage print jobs; internal resources: a system configuration manager handling property files.

2. Windows Task Manager is a typical singleton; you cannot open two instances simultaneously.

3. Windows Recycle Bin maintains a single instance throughout system operation.

4. Web site counters often use a singleton to ensure synchronization.

5. Application logging typically uses a singleton to keep the log file open for appending.

6. Configuration objects in web applications are usually singletons because the configuration file is a shared resource.

7. Database connection pools are commonly implemented as singletons to reduce the overhead of opening and closing connections.

8. Thread pool designs in multithreaded environments often use a singleton to manage threads.

9. An operating system’s file system is a large‑scale singleton; only one file system exists per OS.

10. HttpApplication in ASP.NET is a singleton; all HttpModules share the same instance.

Reference: www.cnblogs.com/damsoft/
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.

JavaSoftware Architecturedesign patternObject-OrientedSingleton
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.