Idiomatic Go design pattern analog for thread-local storage case in Java

1064 views
Skip to first unread message

W. David Jarvis

unread,
Feb 4, 2016, 11:11:36 AM2/4/16
to golang-nuts
Hello, all. 

Long time listener, first time caller.

Here's the situation I'm in. I got bored and started writing a compiler from Clojure to the Go runtime. At the moment, I'm struggling with how to translate the JVM's concurrency idioms for Clojure `Vars` over to Go. In particular, Clojure Vars rely on thread-local storage (ref: https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/Var.java#L67). The use case for this isn't immediately obvious, but in essence it enables downstream local bindings within Clojure source code that don't clobber global references.

From what I understand, `x/net/context` exists largely to address problems very similar to this one, but going down that route feels like I could very easily end up having to pass context as an additional function argument to half the functions in the compiler. That feels ugly, though the functional programmer in me is also pleased by it.

Has anyone else run into a similar translation issue to this? What's the recommended path here?

Cheers,

 - V

Ian Lance Taylor

unread,
Feb 4, 2016, 5:20:04 PM2/4/16
to W. David Jarvis, golang-nuts
As you've discovered, Go has nothing comparable to thread-local
storage. This is because in Go it's easy to start a new goroutine.
Should that new goroutine share the thread-local storage or get new
copies? Neither choice is always correct, depending on how the
goroutine is being used. Instead, Go code uses function closures or
explicit value passing, as appropriate.

In order to translate code from a language that does use thread-local
storage, you are going to have to use a context value, as you mention.
That's the best and really the only approach. Yes, it will wind up
everywhere.

Ian

Egon

unread,
Feb 5, 2016, 3:40:57 AM2/5/16
to golang-nuts
Just a nitpick: "Idiomatic Go design pattern" does not really make sense. You have idioms and you have design patterns, they are different things. I have a hard time imagining an idiomatic design pattern.

If you are thinking of a common way of writing something (in some language/situation), then it's an idiom. Not a design pattern.

+ Egon

Forud A

unread,
Feb 5, 2016, 4:23:12 PM2/5/16
to golang-nuts
There is another workaround here : https://github.com/jtolds/gls .
Reply all
Reply to author
Forward
0 new messages