Skip to main content

Command Palette

Search for a command to run...

Singleton Pattern

Published
2 min readView as Markdown
Singleton Pattern

Why Singleton Pattern

  1. Singleton pattern also gives us a global point of access, just like global variables, but without initializing the object beforehand, a global variable gets created when your application starts which is a downside.

How to restrict the class to create only one object and return the same instance every time?

  1. Make the constructor private - This puts restrictions on access. Only sibling methods can call this private constructor.

  2. Create a static getInstance method - This is a static sibling method, so it can be called with class_name.getInstance().

How to create/get the object instance

MyClass.getInstance();

Basic Implementation

This is performing Lazy initialization, Which creates problems when we add threading into the scenario.

Chocolate Factory example

The factory has a chocolate boiler, The job of the boiler is to take in chocolate and milk, bring them to a boil, and then pass them on to the next phase of making chocolate bars.

What is the problem with this?

This is not thread-safe, so there could be many unique cases that can occur like we should not fill if the boiler is already full, this can happen when we introduce threads in it. Please refer below part for the thread-safe version of the chocolate boiler.

The Singleton Pattern ensures a class has only one instance and provides a global point of access to it.

How multithreading can cause the creation of more than one instance of singleton class

The solution is to make the static method synchronized, but synchronization is expensive and can decrease performance by a factor of 100.

We need synchronization only the first time, once uniqueInstance is set we don't need synchronization.

How can we improve multithreading?

  1. Do nothing if the performance of getInstance() isn't critical to your application.

  2. Move to an eagerly created instance rather than a lazily created one.

    1. Here JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.

  3. Use "double-checked locking" to reduce the use of synchronization in getInstance()

Note - Rumors of Singleton being eaten by garbage collectors are greatly exaggerated, priot o java 1.2 now its resolved. Because the reference to object is itself in object.