marshaling (json) map element in struct thread safe?

633 views
Skip to first unread message

Samit Pal

unread,
Aug 18, 2015, 5:35:53 AM8/18/15
to golang-nuts
Hi,

I have a struct which has some nested struct elements. The nested structs are just wrappers around maps with a RWMutex each. The maps will be written to by multiple goroutines. I intend to marshal the struct using json.Marshal() to expose it via an http handler. The question is will the marshalling be thread safe.

Thanks
Samit

Brad Fitzpatrick

unread,
Aug 18, 2015, 5:57:57 AM8/18/15
to Samit Pal, golang-nuts
Nope. It's not safe to read from a map if another goroutine is writing to it.

The json marshalling code certainly won't use your RWMutex for you. (not that you were asking that)

You can verify that it's not safe by using the race detector.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Samit Pal

unread,
Aug 18, 2015, 8:07:24 AM8/18/15
to Brad Fitzpatrick, golang-nuts
I thought so. Thanks!

Matt Harden

unread,
Aug 18, 2015, 11:36:19 AM8/18/15
to Samit Pal, Brad Fitzpatrick, golang-nuts
You can write your own MarshalJSON methods for those structs to grab the read lock while doing the marshaling. The same goes for other serialiers like String.
Reply all
Reply to author
Forward
0 new messages