Learn use of singleton class in java with examples including three examples used in java libraries. Singleton class is majorly used to create single or unique instance and to avoid performance issue.
Singleton class is only the concept or pattern we use in java. However, to solve the problem we can use other methods. But we will be discussing the scenario where singleton can be a good candidate. If you want to refresh singleton class, you can read singleton class in java example.
- Used due to performance issue.
- Maintain and access current state and methods of an object
- Creating a single instance of a module / application
NOTE: Singleton pattern restricts the instantiation of a class to single instance and ensures that only one instance of the class exists in the application.
Here is some real-life example of use of singleton class used in projects and java libraries.
1)Use of singleton class in java application to solve performance issue.
Consider an example, where in an application, within a loop you are creating thousands of objects using new and calling a method of a class frequently. The object is very heavy and constructor of the object is very time consuming.
What performance issue will be there?
First, we are trying to create a heavy object in loop frequently and it goes out of scope immediately. JVM will not be able to clean the un-referenced object fast resulting heavy memory usage and application may hang.
As a solution, we can make the class as singleton class in java, so throughout the application only one object will exit. so, in a within the loop we get the same instance again and again.
This way we don’t have to create object again and again saving construction time. And, JVM will be out of cleaning pain saving huge memory.
Let’s see the results by pseudo code for above scenario implementation without and with singleton class.
Without singleton Car class – This will call constructor again and again
class Car {
Car() {
System.out.println("Constructor....");
}
public void run() {
System.out.println("Car running....");
}
}
public class Test {
public static void foo() {
Car c = new Car();
c.run();
}
public static void main(String[] args) {
// call loop infinitely
while (true) {
foo();
}
}
}
Here is above program demonstration by making the Car class singleton. In the same scenario only single object will be created. You can notice in output that the constructor will be called only a single time.
class Car {
private static Car obj = new Car();
private Car() {
System.out.println("Constructor....");
}
public static Car getInstance(){
return obj;
}
public void run() {
System.out.println("Car running....");
}
}
public class Test {
public static void foo() {
Car c = Car.getInstance();
c.run();
}
public static void main(String[] args) {
// call loop infinitely
while (true) {
foo();
}
}
}
2)Use of singleton class in java to create a single instance of a module / application
If you want to ensure that only a unique instance of an application or module should run even though you try to execute it again and again then we should use singleton class.
Here are 3 singleton examples implemented in java libraries.
i)Unique Desktop class implementation
Here is a code snip example from greapcode desktop class that returns unique desktop. look at the code, first if desktop is null then it will create an object and if not null then will return the same desktop created earlier.
sun.awt.AppContext context = sun.awt.AppContext.getAppContext();
Desktop desktop = (Desktop)context.get(Desktop.class);
if (desktop == null) {
desktop = new Desktop();
context.put(Desktop.class, desktop);
}
return desktop;
ii)Security manager class implementations
This is a code snips from greapcode security manager class. Gets the system security interface. if a security manager has already been established for the current application, then that security manager is returned; otherwise, null is returned. Notice the statement “if a security manager has already been established it will return or else null”, the meaning is that it has only one instance.
public static SecurityManager getSecurityManager() {
return security;
}
iii)Get the current runtime object of an application that has single instance
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running.
Note that Runtime class constructor is private, so no one can create object of it from outside of class. privately an object has been created and this object is returned using getRunTime() method that is static that can be called by using Runtime class name without creating an object.
Source code snip from grepcode runtime class
public class Runtime {
//privately create object of run time class and return it using
// getRuntime() method
private static Runtime currentRuntime = new Runtime();
//Returns the runtime object associated with
//the current Java application. Most of the methods
//of class Runtime are instance methods and must be
//invoked with respect to the current runtime object.
public static Runtime getRuntime() {
return currentRuntime;
}
//Don't let anyone else instantiate this class
private Runtime() {}
}
3)Maintain and share current state of an object between multiple threads.
If a class object is shareable between multiple threads and want to maintain the current state then you can use singleton class. Note that since it is shared we need to take care of synchronization for use of singleton class in java program.
let’s say two treads are there in an application and running infinitely. They want to get the current state of the object and process it using its function. we can make the class singleton and thread can get the same object over and over and process it.