I saw 2 ways of using singleton pattern in golang.
Whats the difference?
What is the best way to follow by considering thread safety also?
If init() solves all problems then what is sync.Once designed for?
Sync Package To The Rescue The right way to implement a singleton pattern in Go is to use the sync package's Once.Do() function. This function makes sure that your specified code is executed only once and never more than once.
Init functions are called only once, after all the variable declarations and before the main function.
According to the Go language specification, init() functions declared across multiple files in a package are processed in alphabetical order of the file name. For example, the init() declaration in a.go file would be processed prior to the init() function declared in file b.go.
It is possible to define multiple init() functions in one file and multiple packages with init() functions. init() functions in a single file will be loaded in the order that they have been declared, while init() functions in multiple packages will be loaded based on the file names used in alphabetical order.
Package init()
functions are guaranteed by the spec to be called only once and all called from a single thread (not to say they couldn't start goroutines, but they're thread safe unless you make them multi-threaded).
The reason you'd use sync.Once
is if you want to control if and when some code is executed. A package init()
function will be called at application start, period. sync.Once
allows you to do things like lazy initialization, for example creating a resource the first time it is requested (but only once, in case multiple "first" requests come in at the same time) rather than at application start; or to only initialize a resource if it is actually going to be needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With