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

-- 
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.

Reply via email to