View on GitHub

Bearded-android-docs

Singleton

Download this project as a .zip file Download this project as a tar.gz file

Created Monday 09 September 2013

When instantiating a singleton, make sure that the instantiator actually instantiates one instance of the object
i.e., take into account ConcurrencyIssues

@Good

class A
{
       static private A instance = new A(); //thread-safe
       static public A getInstance{ return A; }
}

Lazy instantiation:

@Good (lazy instantiation)

class A
{
      private static class Holder 
      {
            static private A instance = new A();
      }
      static public A getInstance() { return Holder.instance; } //thread-safe but doesn't get instantiated until called
}

Bad Example (Old school DoubleCheckedLocking)

Back in the days when it was expensive to enter a synchronized block, people would instantiate a singleton this way:

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

}

The problem with this technique has to do with JavaMemory:CacheCoherence. Even though Objects are stored in the heap, methods often create cached copies of variables and then sync the results with the heap. Suppose this happens:


Sources:

Warnings

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the Single Responsibility Principle: by virtue of the fact that they control their own creation and lifecycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the app. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.
  5. Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.

Links


Backlinks:

MultiThreading:ConcurrencyIssues
comments powered by Disqus