See Singleton Pattern here…
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.
Singleton.java
package me.dhanoop.singleton;
/**
*
* @author dhanoopbhaskar
*/
public class Singleton {
private static final Helper helper = new Helper();
public static Helper getHelper() {
return helper;
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Singleton.getHelper();
}
};
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}
}
Output:
Created Helper Object
Advantages:
- The instance is not constructed until the class is used.
- There is no need of synchronization, which means all the threads will see the same instance even without expensive locking mechanism.
- The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.