Live data from Hacker News

Singleton Pattern in Go

marcio.io

1–10 of 76 posts

Re: Singleton Pattern in Go

#2
It’s worth noting that not only do you need to synchronize access to the singleton, you need to synchronize access to the singleton’s state as well. And even if you manage that at a fine-grained layer, you’re still setting yourself up for all the problems associated with singletons: http://c2.com/cgi/wiki?SingletonsAreEvil.

If you have a bunch of immutable state, then build unexported package variables in the package’s `init` func and export funcs which use those variables.

If you have a bunch of mutable state, then don’t use a singleton.

Re: Singleton Pattern in Go

#3
This is cute, but I think (someone will correct me if I'm wrong) that the real idiom is: things that would be singletons in Java are instead servers managing a channel in Golang.

Re: Singleton Pattern in Go

#4
Your "check-lock-check" code is probably broken (depending on the intricacies of Golang's memory model). If the compiler or CPU reorders any stores to the fields of "instance" after the assignment to "instance" itself, other threads could start working with a partially uninitialized object. Once() uses atomics on the fast path for a reason.

Re: Singleton Pattern in Go

#8
post #5

This seems more idiomatic: func init() { instance = &singleton{} }

If instance can truly be initialized like that, then there's no need for the init() function, just do it at the top level:

var instance = &singleton{}

In fact, a lot of idiomatic Go will ignore the Get() method, exporting the instance itself:

var Instance = &singleton{}

Clearly if you overwrite it, bad things will happen. Don't do that.

There may possibly be a problem with unnecessarily slowing startup times in the case you don't need the singleton and initialization is more complicated than a malloc - in which case, profiling will tell you and you can revert to the method in the blog post.

Remember that Go's strict import/dependency requirements mean you're unlikely to import the package (and trigger the initialization) unless you actually use the singleton.

It is non-idiomatic to use the sync.atomic package.

Post reply on HN