Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always okay to use variables concurrently in Go?

Tags:

json

go

I'm writing a small webserver program, and it does a lot of JSON decoding from POST requests coming in.

Initially I thought that instead of initializing a new json.Decoder every time a request comes in, I have it as a global variable that gets called on every time and decodes concurrently with goroutines.

As a newcomer to Go, is this okay? Are there times when I shouldn't be doing this and classes will freak out due to not being thread safe (I guess "goroutine" safe would be better)?

like image 917
Doug Smith Avatar asked Feb 08 '23 03:02

Doug Smith


1 Answers

In Go, json.NewDecoder takes an io.Reader as an input parameter and returns a *json.Decoder. Hence it is not possible to reuse the same Decoder since we have a different http.Request.Body (which implements io.Reader) for each POST request.

And as mentioned by Paul Hankin, you can't use go objects concurrently unless they're documented to be safe to use concurrently.

Examples :

  1. http.Client & http.Transport

    Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.

Source

  1. Maps

    After long discussion it was decided that the typical use of maps did not require safe access from multiple goroutines.

Source

If you asked about reusing JSON decoder to avoid the duplication of code you could look at frameworks like Tigertonic and Go-Json-Rest.

On a side note you could look at ffjson to speed up JSON Decoding.

like image 166
John S Perayil Avatar answered Feb 11 '23 01:02

John S Perayil