Ralph
Ralph

Reputation: 4868

What is the difference between Singleton Pattern and Synchronized

I have a problem with "thread safe" method calls in one of my Java EE Beans concerning using the Lucene IndexWriter.

I am unsure if I should solve my problem by implementing a Singleton Pattern or if it is sufficient to add the keyword synchronized to my bean methods.

Can anybody explain what exactly is the difference?

Upvotes: 0

Views: 1187

Answers (2)

Gonzo Gonzales
Gonzo Gonzales

Reputation: 133

Singleton creates exactly one instance of a class. As long as it isn’t referenced by itself.

As an example of a non-thread-safe method:

public class Singleton {

  private static Singleton instance;
  private Singleton () {}

  public static Singleton getInstance () {
    if (Singleton.instance == null) {
      Singleton.instance = new Singleton ();
    }
    return Singleton.instance;
  }
}

The problem with this is: If more than one thread execute getInstance simultaneously for the first time, the constructor of Singleton is called more than once. So the singleton would not be a singleton and subsequent errors are very hard to detect.

Examples of a thread-safe method:

public class Singleton {

  private static Singleton instance;
  private Singleton () {}
  public static synchronized Singleton getInstance () {
    if (Singleton.instance == null) {
      Singleton.instance = new Singleton ();
    }
    return Singleton.instance;
  }
}

The bad thing about this method is that for every access the getInstance method is called (so one thread could block others).

Last but not least the synchronized version:

public class Singleton {
  private static final class InstanceHolder {
    static final Singleton INSTANCE = new Singleton();
  }
  private Singleton () {}
  public static Singleton getInstance () {
    return InstanceHolder.INSTANCE;
  }
}

Initialization of class variables is implicitly synchronized by the class loader. By using the inner class Singleton-Constructor, it’s only called during the initialization of the inner class in the getInstance method.

I hope this helps you. And sorry for my bad english if you need more information just post a comment.

Upvotes: 3

SKU_MIG
SKU_MIG

Reputation: 21

Singleton pattern is one object concept across jvm or application instance, whereas synchronized is a keyword in java to for mutual exclusion. Please elaborate your problem.

Upvotes: 0

Related Questions