Singleton Pattern in Java

Arjun Sunil Kumar
Software Engineering
2 min readAug 18, 2018

This has the same purpose as static variable in java. Can be initialized only once!

Problem solved :

Creating multiple objects of java class having same data is wasting memory, degrading performance. It is recommended to create one object and use it multiple times (at certain use-case)

When to use?

  • For a class which does not contain attribute or any state. (E.g. Conversion class, Validation class)
  • The class, for which we want to create only one object or instance. (Logger, Database etc)
  • In Firebase, database instance is created only once:
Android : com.google.firebase:firebase-core:16.*
Firebase getInstance() is singleton implementation.

Code Findings:

Redux-Store is an singleton state tree.
  • It is used in react-redux (I believe). If you see, the redux store is initialized only once.

store.js

containers/Component.js

redux store is apparently the single point of state data.

Example again:

Suppose your back-end is live. During some point in time, there where some Exceptions thrown. In the end of the day, these Exceptions are to be pushed into the DB and analysed.

For this scenario, we need to keep a single object(Exception Queue) to hold Exceptions thrown from various Classes, rather than, instantiating a new Exception Queue every time.

Project Structure:

Implementation in Java:

  1. Singleton Class is created
  • private constructor
  • public Class getInstance() calls the private constructor

2. Driver to test the program

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

Reference:

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

--

--

Arjun Sunil Kumar
Software Engineering

Writes on Database Kernel, Distributed Systems, Cloud Technology, Data Engineering & SDE Paradigm. github.com/arjunsk