singleton pattern

http://en.wikipedia.org/wiki/Singleton_pattern

Example

The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.

Lazy initialization

This method uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs. The problem is that an out-of-order write may allow the instance reference to be returned before the Singleton constructor is executed.[9]

public class SingletonDemo {
        private static volatile SingletonDemo instance = null;

        private SingletonDemo() {       }

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

Eager initialization

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

This method has a number of advantages:

  • The instance is not constructed until the class is used.
  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

Why the lazy double-check work?

http://www.ibm.com/developerworks/java/library/j-dcl/index.html

Listing 4. Double-checked locking example

                
public static Singleton getInstance()
{
  if (instance == null)
  {
    synchronized(Singleton.class) {  //1
      if (instance == null)          //2
        instance = new Singleton();  //3
    }
  }
  return instance;
}

The theory behind double-checked locking is that the second check at //2 makes it impossible for two different Singleton objects to be created as occurred in Listing 3. Consider the following sequence of events:

  1. Thread 1 enters the getInstance() method.
  2. Thread 1 enters the synchronized block at //1 because instance is null.
  3. Thread 1 is preempted by thread 2.
  4. Thread 2 enters the getInstance() method.
  5. Thread 2 attempts to acquire the lock at //1 because instance is still null. However, because thread 1 holds the lock, thread 2 blocks at //1.
  6. Thread 2 is preempted by thread 1.
  7. Thread 1 executes and because instance is still null at //2, creates a Singleton object and assigns its reference to instance.
  8. Thread 1 exits the synchronized block and returns instance from the getInstance() method.
  9. Thread 1 is preempted by thread 2.
  10. Thread 2 acquires the lock at //1 and checks to see if instance is null.
  11. Because instance is non-null, a second Singleton object is not created and the one created by thread 1 is returned.

Note: think about if there is no line #2, there will be the case each thread return a different instance

related links: http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104

http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s