- Singleton is a class which has only one instance in whole application and provide getInstance() method to access singleton instance.
- There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.
Example:
[1] Singleton by private static field, static getInstance() method:
- public class SingletonExe {
- private static SingletonExe instance = null;
- private void SingeltonExe() {
- System.out.println("Private constructor");
- }
- public static SingletonExe getInstance() {
- if (instance == null) {
- synchronized (SingletonExe.class) {
- if (instance == null) {
- instance = new SingletonExe();
- }
- }
- }
- return instance;
- }
- }
[2] Singleton by synchronized getInstance() method [double checked locking in Singleton]
/**
* Java program to demonstrate where to use Volatile keyword in Java. In this
* example Singleton Instance is declared as volatile variable to ensure every
* thread
*/
- public class SingletonExe {
- private static volatile SingletonExe instance = null; // volatile variables
- private void SingeltonExe() {
- System.out.println("Private constructor");
- }
- public static SingletonExe getInstance() {
- if (instance == null) {
- synchronized (SingletonExe.class) {
- if (instance == null) {
- instance = new SingletonExe();
- }
- }
- }
- return instance;
- }
- }
No comments:
Post a Comment