Iced Tea Labs Share to be shared

Singleton Implementation

A - Intent

B - Usage

Singleton will be applied when you want to have exactly ONE instance of a class, no less, no more. And that object can be access anywhere in your code.

Some cases that Singleton is usually used:

C - Singleton Structure

java-singleton-design-pattern

Singleton is the simplest design pattern (that’s why I wrote an entry about it LOL).

As you can see in the firgure above, a Singleton class consists of:

That’s all. Only one class :)))

D - Singleton Implementation

1. Lazy initialization

This way is a classical Singleton implementation.

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

Pros:

Cons:

To prevent multi-thread concurrency, let’s take a look at the second way!

2. Eager initialization

The easiest way to prevent multi-thread concurrency is eager initialization.

private Singleton instance = new Singleton();

public static getInstance(){
	return instance
}

Pros:

Cons:

3. Thread safe with lazy initialization

If you want to resolve all the disadvantages of eager initialization, try this way:

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

	return instance
}

With the synchronized keyword, you can handle multi-thread concurrency case but it will be very costly. That’s why I use the double check locking mechanism( cehck in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block). If we see that the singleton object is already created we just have to return it without using any syncronized block.

Pros:

Cons:

4. Enum Singleton

You also can using Enum to implement Singleton:

public enum Singleton {
	Singleton instance;
	public void doStuff(){
		return instance;
	}

}

Pros:

Cons:

E - Singleton vs Static Class

Anything else? Just comment below! :)

 

comments powered by Disqus