Singleton class in java

What is a singleton class?

You can find multiple definitions in Google for singleton class but as I am sharing my research work with you guys, I will start with the definition first and then I will take you through my research.
Definition:-
Singleton class is a class which has a single instance whole application and provides an getInstance() method for accessing the singleton instance.

Example:-

Java.lang.Runtime which provides getRuntime() method for getting access of it and used memory information in Java
package org.stacktrace.singletonclass;

public class SingleTonClass {

/**
* @param args
*/
public static void main(String[] args) {

Runtime r = Runtime.getRuntime();
System.out.println(“free memory ===== > “+r.freeMemory());
System.out.println(“max memory =====> “+r.maxMemory());

}

}

Purpose of singleton class in JAVA:-

Purpose of singleton class is to create only one instance for total application. So what happens if we have only one single instance for total application?
With singleton there will be only one instance of the class per JVM. Most often application specific things can go in singleton. For ex: if you want to design an application such that some information needs to be shared with various clients you can keep this information in singleton class.
The real advantage is when you make heavy weight class singleton, you are sharing a single instance of that class with multiple threads which saves resources and time.

Now we know the real purpose of creating a singleton class lets create our own singleton class .
Implementing singleton:-
1)First lets create a singleton class.

Singleton_Implementation
package org.stacktrace.singletonclass;

public class SingleClass {

/* making class instance as private and static. So that it can only be accessed
* only from static block .
* getInstance() method will return this class instance and which is public .
*/

private static SingleClass single = new SingleClass();
private SingleClass(){};

public static SingleClass getInstance(){
return single;

}

public String sayHello(){

return “Hello, I am a singleton class”;
}

}

2) Main Class for accessing the singleton class.


package org.stacktrace.singletonclass;

public class SingleTonClass {

/**
* @param args
*/
public static void main(String[] args) {

// Accessing the singleton class instance inside a static method
SingleClass s = SingleClass.getInstance();
System.out.println(s.sayHello());

}

}

I will continue in depth about singleton class in my next post and will take about types of implementing singleton class in java.

Related posts:

Comments

comments

Powered by Facebook Comments

%d bloggers like this: