Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Singletons

Name: Anonymous 2009-01-09 5:18

A toast for one of my favorite ways to create and interact with things. I love you, singleton. And there's only one of you.

Name: Anonymous 2009-01-10 15:15

>>22
Your version is still not thread safe. Due to the JAVA memory model, one thread may acquire the lock, see that enterpriseSingleton is null, and begin instantiating it. Before the instantiation has finished, another thread may observe the enterpriseSingleton as being non-null, and so attempt to use the object when it is only partly initialized.

Here is a version that fixes the problem.

public class EnterpriseSingleton {
  private static EnterpriseSingleton enterpriseSingleton;

  private EnterpriseSingleton() {
  }

  public static EnterpriseSingleton getInstance() {
    if (enterpriseSingleton == null) {
      EnterpriseSingleton temp;
      synchronized (EnterpriseSingleton.class) {
        if (enterpriseSingleton == null) {
          temp = new EnterpriseSingleton();
        }
        synchronized (EnterpriseSingleton.class) {
          enterpriseSingleton = temp;
        }
      }
    }
    return enterpriseSingleton;
  }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List