Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between init() and sync.Once in golang [closed]

Tags:

go

I saw 2 ways of using singleton pattern in golang.

  1. Using init() functions
  2. Using sync.Once in sync package

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?

like image 883
lokanadham100 Avatar asked Aug 21 '18 16:08

lokanadham100


People also ask

What is sync once in Golang?

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.

Is INIT called only once?

Init functions are called only once, after all the variable declarations and before the main function.

What is Init method in Golang?

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.

Can you define multiple init () functions in the same .Go file?

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.


1 Answers

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.

like image 85
Adrian Avatar answered Oct 21 '22 16:10

Adrian