Home » Core Java » Java Singleton Design Pattern Example

About Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.

Java Singleton Design Pattern Example

1. Introduction

In this article, we would be focusing on one of the many Java design patterns – The Java Singleton Design pattern with the help of a real-life example.

In a massive Java application developed for a large organization, often it ends up hard to oversee and comprehend the code. With a fluctuating profile of designers taking a shot at a similar task, it is essential that the code being produced is justifiable by new engineers that join the undertaking. This is conceivable just when there are guidelines set up. These benchmarks ought to be intended to structural or build up the code in a way that is as of now expected by the new engineers. The Java people group has henceforth indicated a few plan patterns. In each pattern there are sure pre-characterised coding principles and structures to be pursued. These particular measures and the structures of code aid advancement of a code that is sorted out and effectively sensible. In addition, it likewise discovers that the code is sorted out in a predefined way and along these lines it is effectively reasonable by any new engineer joining the undertaking.

With the end goal to guarantee that these coding structures are institutionalised, Java characterises a substantial group of configuration patterns which spin around the different parts of coding like how we characterise a particular class, how we connect the classes to utilize other, how we use the center highlights of Java like the inheritance and interfaces, the making of objects and the administration of protest conduct.

2. Java Design patterns

There are three essential gatherings of these plan patterns which are quickly clarified underneath.

2.1 Creational Pattern

This gathering of patterns gives five distinctive outline patterns that principally center around the rationale of creation and decimation of objects while covering the genuine execution of the objects. This essentially characterizes the norms for deliberation. Along these lines, this pattern controls the protest access for every module that exists in the application.

2.2 Structural Pattern

This gathering of patterns gives us seven unique patterns to enable the engineers to compose the class structure with the goal that the coveted classes and highlights are uncovered in a coveted way. Moreover, they offer answers for issues like interfacing distinctive kinds of objects, substances or applications. They likewise control in tackling the issues of isolating unique classes from the genuine usage. This is the place bridge pattern fundamentally has a place.

2.3 Behavioural Pattern

This pattern classification is for the most part connected with the manner in which objects speak with one another. This incorporates messaging lines, passing messages by means of interfacing classes and others. There are about eleven such patterns to characterise the specialised philosophies.

In this article, we would talk about one of the design patterns – the Singleton design pattern. The article would clarify the idea driving this pattern with a genuine model to enable you to pick up a knowledge on how the design pattern has truly helped improve a object instantiation. The following area covers the pattern legitimately to clarify every segment of the Singleton pattern designing in a project to set you up to comprehend the code that lies ahead.

3. Understanding the Java Singleton Design pattern

One of the hardest issues to investigate is the one made by the numerous cases of a class which deals with the condition of a solitary asset. It is very alluring on the off chance that we can utilize some Design Pattern to control the entrance to that common asset. The Singleton pattern possesses all the necessary qualities flawlessly to comprehend this situation; by wrapping a singleton class around this issue guarantees that there will be just a single occasion of the class at some random time. A most normal and unoriginal case for a singleton class is the one utilized for logging purposes where the entire application needs just a single logger occurrence at whenever.

Java Singleton Pattern is one of the four creational Design examples and comes in the Creational Design Pattern class. From the definition, it is by all accounts an exceptionally basic design yet with regards to its usage, it accompanies a ton of execution concerns. The usage of Java Singleton design has dependably been a dubious point among engineers. The question that stands is what exactly is the Singleton Design pattern. Below points aptly describe what Singleton pattern exactly is.

  • Singleton design limits the instantiation of a class and guarantees that just a single occasion of the class exists in the java virtual machine.
  • The singleton class must give a worldwide passageway to get the occurrence of the class.
  • Singleton design is utilized for logging, drivers questions, reserving and string pool.
  • Singleton design is additionally utilized in other design designs like Abstract Factory, Builder, Prototype, Facade and so forth.
  • Singleton design is utilized in center java classes likewise, for instance java.lang.Runtime, java.awt.Desktop.

In an enterprise scale application, it becomes highly important to manage the memory efficiently. With Java Singleton pattern, we create only a single instance of object each time which reduces the memory occupancy considerably. Despite the simplicity of the Singleton pattern, the pattern holds a great importance in the industry and popular frameworks like Hibernate, Spring, Struts use this pattern inherently. They provide implementations and configurations to make a class Singleton by nature.

Although these frameworks provide such a feature readily, there are occasions where we might have to develop a project from scratch without the framework library overhead. In such a case, we need to develop the code to expose a class in a Singleton manner. The next section discusses in detail about how to implement a Singleton design pattern.

4. Coding Singleton pattern with example

MySingletonClass.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
package com.javacodegeeks.abk;
public class MySingletonClass {
        private static MySingletonClass obj;
        private MySingletonClass() {}
      
        public static MySingletonClass getInstance()
        {
            if (obj==null)
                obj = new MySingletonClass();
            return obj;
        }
    
}

The above code is a very simple implementation of the Singleton design pattern. In the above code, we developed a class that creates an instance of itself and return it when needed. The getInstance function basically checks for existence of an instance first and if it does not exist, it creates a new one. However, the point to be noted here is that an object is created only when needed. This points out to the different ways of initialising these objects. Thus, Singleton pattern has a variety of initialisations possible. Each of them are explain below.

4.1 Eager initialisation

In eager initialisation, the case of Singleton Class is made at the season of class stacking, this is the least demanding strategy to make a singleton class yet it has a disadvantage that occasion is made despite the fact that customer application probably won’t utilize it.

Here is the usage of static initialisations singleton class.

StaticSingleton.java

01
02
03
04
05
06
07
08
09
10
11
12
package com.javacodegeeks.abk;
public class EagerSingleton {
    
    private static final EagerSingleton instance = new EagerSingleton();
    
    //private constructor to restrict the clients from use of this constructor
    private EagerSingleton(){}
    public static EagerSingleton getInstance(){
        return instance;
    }
}

On the off chance that your singleton class isn’t utilising a great deal of assets, this is the way to deal with utilize. Be that as it may, in the vast majority of the situations, Singleton classes are made for assets, for example, File System, Database associations and so on and we ought to maintain a strategic distance from the instantiation until the point that except if customer calls the getInstance technique. Likewise this strategy doesn’t give any alternatives to exemption dealing with.

4.2 Static block initialisation

Static block initialisation execution is like eager initialisations, with the exception of that case of class is made in the static block that gives alternative to special case taking care of.

StaticSingleton.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
public class StaticSingleton {
    private static StaticSingleton instance;
    
    private StaticSingleton(){}
    
    //static block creaton of object for exception handling
    static{
        try{
            instance = new StaticSingleton();
        }catch(Exception e){
            throw new RuntimeException("Exception occurred in creating singleton instance");
        }
    }
    
    public static StaticSingleton getInstance(){
        return instance;
    }
}

Both eager initialisation and static block initialisation makes the occurrence even before it’s being utilized and that isn’t the best practice to utilize. So in further segments, we will figure out how to make Singleton class that backings lazy initialisation.

4.3 Lazy Initialisation

Lazy initialisation strategy to instantiate Singleton design makes the example in the worldwide access technique. The first example that we saw is actually the perfect example of Lazy initialisation.
The above usage works fine incase of single threaded condition yet with regards to multithreaded frameworks, it can cause issues if different threads are inside the if circle in the meantime. It will demolish the singleton design and the two threads will get the diverse occasions of singleton class. In next area, we will see distinctive approaches to make a thread-safe singleton class.

4.4 Thread Safe Singleton

The simpler method to make a thread-safe singleton class is to make the worldwide access strategy synchronized, with the goal that just a single thread can execute this technique at once. General execution of this methodology resembles the underneath class.

ThreadSafeSingleton.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package com.javacodegeeks.abk;
public class ThreadSafeSingleton {
    private static ThreadSafeSingleton instance;
    
    private ThreadSafeSingleton(){}
    
    public static synchronized ThreadSafeSingleton getInstance(){
        if(instance == null){
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
    
}

Above usage works fine and gives thread-safety however it diminishes the execution in view of expense related with the synchronized technique, in spite of the fact that we require it just for the initial couple of threads who may make the different examples (Read: Java Synchronization). To keep away from this additional overhead unfailingly, twofold checked bolting guideline is utilized. In this methodology, the synchronized block is utilized inside the if condition with an extra check to guarantee that just a single occurrence of singleton class is made. Below code snippet gives the twofold checked bolting execution.

LockSafeSingleton.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package com.javacodegeeks.abk;
public class LockSafeSingleton {
    private static LockSafeSingleton instance;
    
    private LockSafeSingleton(){}
    
    public static LockSafeSingleton getInstanceUsingDoubleLocking(){
        if(instance == null){
            synchronized (LockSafeSingleton.class) {
                if(instance == null){
                    instance = new LockSafeSingleton();
                }
            }
        }
        return instance;
    }
    
}

5. Uses of Singleton Design Pattern

Various uses of Singleton Patterns:

Access to Hardware interfaces: The utilization of singleton relies upon the necessities. Anyway for all intents and purposes singleton can be utilized on the off chance that outside equipment asset use constraint required e.g. Equipment printers where the print spooler can be made a singleton to maintain a strategic distance from various simultaneous gets to and making gridlock.

Logging & Error Handling : Similarly singleton is a decent potential possibility for utilizing in the log records age. Envision an application where the logging utility needs to deliver one log record dependent on the messages got from the clients. On the off chance that there is different customer application utilizing this logging utility class they may make various occurrences of this class and it can conceivably make issues amid simultaneous access a similar lumberjack record. We can utilize the lumberjack utility class as a singleton and give a worldwide perspective.

Configuration Files: This is another potential possibility for Singleton pattern since this has an execution advantage as it keeps various clients to more than once access and read the arrangement record or properties document. It makes a solitary case of the setup record which can be gotten to by various calls simultaneously as it will give static config information stacked into in-memory objects. The application just peruses from the design document at the first run through and there after from second call onwards the customer applications read the information from in-memory objects.

Caching and Connections handling: We can utilize the store as a singleton question as it can have a worldwide perspective and for every future call to the store make sure the customer application will utilize the in-memory caching with singleton design pattern. Additionally, frameworks like Hibernate also uses Singleton patterns for its connection factories.

6. Conclusion

Java Singleton design pattern has been defined to make sure that the high-end Java applications are optimised to use instantiate the objects on as needed. The singleton design pattern also makes sure that the object sharing between threads is well-managed and there is no data inconsistency due to it. The Singleton pattern has numerous ways of implementing it. However, the majority of the varieties have been discussed above. You can always read further to know about more ways of implementing the pattern.

7. Download the Source Code

The attached file below contains a simple Eclipse Java project with the above defined classes. You can download the same by clicking on the below box.

Download
You can download the full source code of this example here: SingletonPattern.zip
(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Trenton D. Adams Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Trenton D. Adams
Guest
Trenton D. Adams

You put a lot of effort, and a lot of code, into something that was solved with Java 5. I recommend getting a copy of effective Java by Joshua block. The Java enum provides all of the facilities you mention here, with virtually no code, and not much need to think.