Golang : How to run your code only once with sync.Once object
Problem :
You have a function that will load a resource such as reading configuration data from an external file as part of the initialization process. However, each time when the main program calls the function, it will read the configuration data again and again.
How to ensure that certain part of the function only execute once only? Load once instead of reading the configuration data again and again?
Solution :
Use the sync.Once
object. Below is an example that demonstrates how sync.Once
object can be used to wrap some part of the code inside a function to only execute once.
package main
import (
"fmt"
"strings"
"sync"
)
var configurationFile = "configuration_data = x"
var onlyOnce sync.Once
var config strings.Reader
func main() {
getData()
go getData()
go getData()
getData()
// keep running until user press Control-C
for {
}
}
//---------------------------------------------------------------------------------------
func getData() {
// we only want to load the configuration once
onlyOnce.Do(func() {
fmt.Println("Load run-time configuration first and the only time. ")
config = *strings.NewReader(configurationFile)
})
fmt.Println(config)
}
Output:
2019/06/18 10:00:00 Load run-time configuration first and the only time.
2019/06/18 10:00:00 {configuration_data = x 0 -1}
2019/06/18 10:00:00 {configuration_data = x 0 -1}
2019/06/18 10:00:00 {configuration_data = x 0 -1}
2019/06/18 10:00:00 {configuration_data = x 0 -1}
Happy coding!
References :
https://golang.org/pkg/sync/#Once
https://www.socketloop.com/references/golang-strings-newreader-function-example
See also : Golang : A program that contain another program and executes it during run-time
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.5k Gogland : Single File versus Go Application Run Configurations
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+10.8k Golang : Removes punctuation or defined delimiter from the user's input
+17.2k Golang : How to tell if a file is compressed either gzip or zip ?
+7.8k Golang : Trim everything onward after a word
+32.6k Golang : Regular Expression for alphanumeric and underscore
+7.9k Golang : Handle Palindrome string with case sensitivity and unicode
+4.9k Nginx and PageSpeed build from source CentOS example
+12.5k Golang : Exit, terminating or aborting a program
+40k Golang : UDP client server read write example
+24k Golang : Upload to S3 with official aws-sdk-go package
+37.6k Golang : Comparing date or timestamp