The Singleton pattern is a design pattern that restricts the instantiation of a class to a single instance, ensuring controlled access to that instance globally throughout an application.
We can check that using "Race Data Detector" from golang, it is "-race" parameter to check race detector, which helps identify data races in concurrent programs, for example if there are two or more goroutines acessing the same varibles concurrently. Data Race Detector
You can do that in two different ways:
- Not thread Safe - golang-singleton-unsafe.go
- here race detector point 2-4 data races, can cause a deadlock
- Thread Safe - golang-singleton-once.go
- here we are using sync.Once that is a synchronization primitive that ensure a function is executed exactly once, even across multiples goroutines
-
Controlled Access: Global point of access to the instance, ensuring that all parts of the application use the same instance
-
Lazy Initialization: The instane can be created only when it is needed
-
Reduced Memory Footprint: Only one instance exists, it saving memory
-
Simplified Code: Simplify the codebase and reduces the complexity of object creation
-
Thread Safety: When implemented for, it can be made thread-safe, preventing issues in multi-threaded environments
-
Configuration Management: applications settings or configurations, ensure that all the app access same configuration instance
-
Logging: Ensure that all log messages are sent to the same log file or output stream, maintaining consistency and avoid conflicts
-
Database Connections: Single database connection pool, reducing overhead of creating multiple connections.
-
Resource Management: Manage shared resources, such as thread pools or caches, Singleton ensure that all components interact with same resource manager
-
Event Handling: sometimes a single event manager is nedded to hanle events across different parts of the application, it can be centralized using Singleton
-
Service Locators: If you are implementing a service locator pattern, using a Singleton to manage service instances can streamline access to those services
go run -race golang-singleton-once.go
and
go run -race golang-singleton-unsafe.go
Sequence diagram
Architecture