by BehindJava

Real time example of a singleton design pattern in Java

Home » java » Real time example of a singleton design pattern in Java

In this tutorial we are going to learn about singleton design pattern in Java with real time examples.

Singleton Design Pattern in object oriented programming is a class that can have only one object i.e., single instance of a class at a time.

In terms of instantiation for a singleton class we use getInstance() method and for a normal class we use constructor.

For example, let’s say we have to define a class that has only one instance and provides global point of access to it where a class must ensure that only single instance should be created and single object can be used by all other classes.

There are two forms of singleton design pattern:

  1. Early Instantiation: creation of instance at load time.
  2. Lazy Instantiation: creation if instance when required.

Advantages and uses of singleton design pattern:

  • Saves memory because object is not created at each request where single instance is reused again and again.
  • Singleton pattern is mostly used in multi-threaded and database applications.

Sample Code Snippet:

public class Singleton {
	private static Singleton singleton_instance=null;
	private Singleton()
	public static Singleton getInstance()
		if(singleton_instance==null) {
			singleton_instance =new Singleton();
		return singleton_instance;
	public void connection()
		System.out.println("connected to database");
	public static void main(String[] args)
		Singleton s1;


connected to database

As described by the pattern, any time you want there to exist only a single instance of something, you would use the Singleton Pattern.

A common example might be a Logger object. There could be many places throughout the system where one would invoke a logger to, well, log something. But you may only ever need one such instance. This can be particularly true if constructing the instance is a heavy operation.

Something like this:

public class Logger {
    private static final Logger INSTANCE = new Logger();

    private Logger() {
        // do something to initialize the logger

    public static Logger getInstance() {
        return INSTANCE;

    // implementation ...

Then any code which needs to reference the logger doesn’t need to instantiate it (can’t, in fact), and instead just uses the singleton:

Logger.getInstance().Log("some message");

Other real-world examples might include a dependency injection container, a read-only data access service (such as a lookup service which caches results), etc. Generally anything where initialization or repeated operations can be heavy and which is thread-safe.