On Thu, Dec 6, 2018 at 8:45 PM Chao Yuepan <smalln...@gmail.com> wrote: > > Java implements singleton by double-checking must use keyword volatile : > > > class Foo { > private volatile Bar bar; > > public Bar getBar() { > Bar value = bar; > if (value == null) { > synchronized (this) { > value = bar; > if (value == null) { > bar = value = computeBar(); > } > } > } > return value; > } > > private Bar computeBar() { ... } > } > > > > I want to know whether the double-checking just like this is safe? > > package main > > import ( > "sync" > ) > > type Foo struct { > Bar int > } > > var foo *Foo > var mu sync.Mutex > > func GetSingleton() *Foo { > if foo == nil { > mu.Lock() > if foo == nil { > foo = &Foo{Bar: 100} > } > mu.Unlock() > } > > return foo > } > > > > > > I know we can use atomic or sync.Once to implement go singleton. And some > double-checking is not right as described at https://golang.org/ref/mem
This is not safe. Don't do it. Use sync.Once. (It's not safe because in the absence of any synchronization it is possible that another thread will see that foo is not nil but will not see the values to which foo points.) Ian -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.