In "SingletonClass pattern" post I have discussed about singleton pattern. In this article, I am going to explain, several ways of creating singleton class.
As we known singleton pattern widely used for creating a one and only instance for a class.
Here is the list of the ways we can create singleton class,
The instance creation of the class during class loading itself and even the constructor of the class called. Like below we can create static singleton class.
As we known singleton pattern widely used for creating a one and only instance for a class.
Here is the list of the ways we can create singleton class,
- Static Blocks.
- Eager initialization.
- Lazy initialization.
- Enums.
- Static blocks
The instance creation of the class during class loading itself and even the constructor of the class called. Like below we can create static singleton class.
- Eager initialization.
In Eager initialization is one of the best approach to create singleton class. The instance of an class are created much before it is actually required. So the class instance is required or not but this will be created.
- Lazy initialization.
In the above method, we have drawback whether the instance required or not we are creating a single instance and keep in memory. Even if it is not used in the application we are creating it. To avoid this, we have to use Lazy initialization. we have to create a object when required like shown below.
In this above implementation is not suitable for multi threaded environment because two threads such as Thread1 and Thread2 possess the "Obj" value as "null". We have to make synchronized block the getinstance method for mutli threaded application using double check mechanism like below,
The above code is thread safe now. Even several thread access getInstance method the synchronized method blocks other threads, complete it one by one.
No comments:
Post a Comment