Singleton design pattern in Java
In object-oriented programming, the Singleton pattern exerts its influence by confining the instantiation of a class and assuring the exclusive existence of a solitary instance within the Java Virtual Machine (JVM). Put simply, this pattern demands that a class guarantees the creation of just a solitary instance, serving as a unified entity accessible by all other classes.
Usage of Singleton Pattern
When the requirement arises to guarantee the presence of a single instance of an object accessible to multiple other classes, the utilization of the Singleton pattern becomes advantageous.
Advantage
- Singleton Pattern can saves memory because object is not created at each request.
- Provide a global point of access to the object.
- Allow multiple instances in the future without affecting a singleton class's clients.
How to create Singleton design pattern?
In order to create a Singleton Pattern, you need the following:
- Static member: It gets memory only once because of static, it contains the instance of the Singleton class.
- Private constructor: It will prevent to instantiate the Singleton class from outside the class.
- Static factory method: It provides the global point of access to the Singleton object and returns the instance to the caller.
In the SingletonClass, first time when we request first time call getInstance() method, it creates an object of the class with name sInstance and return it to the variable.
In the SingletonClass, the initial invocation of the getInstance() method results in the creation of an object named sInstance within the class, which is subsequently returned and assigned to the variable.
As sInstance is declared as static, it undergoes a transformation from a null value to an instantiated object during the initial invocation of the getInstance() method. Subsequent calls to getInstance() will detect that sInstance is no longer null, and thus, the existing object will be returned to the variable instead of creating a new instance of the SingletonClass.
Within the main method, when the singleton class is instantiated using the static method getInstance(), three objects obj1, obj2, and obj3 are created. However, in reality, obj2 and obj3 are assigned references to the same object as obj1. As a result, any modifications made to the variables of obj1 will be reflected when accessing the variables of obj2 and obj3. Similarly, changes made to the variables of obj3 will be observed when accessing the variables of obj1 and obj2, due to their shared reference to the same underlying object.
Difference between Normal class and Singleton class
There is a distinction in the instantiation process between a normal class and a singleton class.
In a normal class, object instantiation is typically performed using a constructor. You can create multiple instances of the class by invoking the constructor with the new keyword, allowing you to have multiple independent objects of that class.
On the other hand, a singleton class enforces the presence of only a single instance throughout the application. Instead of directly calling the constructor, you use a specialized method, often named getInstance(), to retrieve the sole instance of the class. This method is responsible for ensuring that only one instance is created and returned, regardless of the number of times it is invoked.
The use of the getInstance() method in a singleton class allows for centralized control over the object's creation, ensuring that multiple instances are not inadvertently created. This design pattern is often employed when there is a need to have a single, shared instance that can be accessed globally within the application.
Difference between static class and singleton pattern
- Singleton objects are stored in Heap, but static objects are stored in stack.
- We can clone the singleton object, but we cannot clone the static class object .
- Singleton classes follow the OOP concepts), static classes do not.
- You can create one instance of the object and reuse it whereas you cannot create the instance of static class.
Conclusion
The Singleton design pattern in Java ensures that only one instance of a class is created and provides a global point of access to that instance.
- Java Interview Questions-Core Faq - 1
- Java Interview Questions-Core Faq - 2
- Java Interview Questions-Core Faq - 3
- Features of Java Programming Language (2024)
- Difference between Java and JavaScript?
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Generics in Java
- Static keyword in Java
- What are final variables in Java?
- How Do Annotations Work in Java?
- How do I use the ternary operator in Java?
- What is instanceof keyword in Java?
- How ClassLoader Works in Java?
- What are fail-safe and fail-fast Iterators in Java
- What are method references in Java?
- "Cannot Find Symbol" compile error
- Difference between system.gc() and runtime.gc()
- How to convert TimeStamp to Date in Java?
- Does garbage collection guarantee that a program will not run out of memory?
- How setting an Object to null help Garbage Collection?
- How do objects become eligible for garbage collection?
- How to calculate date difference in Java
- Difference between Path and Classpath in Java
- Is Java "pass-by-reference" or "pass-by-value"?
- Difference between static and nonstatic methods java
- Why Java does not support pointers?
- What is a package in Java?
- What are wrapper classes in Java?
- Difference between Java Local Variable, Instance Variable and a Class Variable?
- Can a top level class be private or protected in Java
- Are Polymorphism , Overloading and Overriding similar concepts?
- Locking Mechanism in Java
- Why Multiple Inheritance is Not Supported in Java
- Why Java is not a pure Object Oriented language?
- Static class in Java
- Difference between Abstract class and Interface in Java
- Why do I need to override the equals and hashCode methods in Java?
- Why does Java not support operator overloading?
- Anonymous Classes in Java
- Static Vs Dynamic class loading in Java
- Why am I getting a NoClassDefFoundError in Java?
- How to Generate Random Number in Java
- What's the meaning of System.out.println in Java?
- What is the purpose of Runtime and System class in Java?
- The finally Block in Java
- Difference between final, finally and finalize
- What is try-with-resources in java?
- What is a stacktrace?
- Why String is immutable in Java ?
- What are different ways to create a string object in Java?
- Difference between String and StringBuffer/StringBuilder in Java
- Difference between creating String as new() and literal | Java
- How do I convert String to Date object in Java?
- How do I create a Java string from the contents of a file?
- What actually causes a StackOverflow error in Java?
- Why is char[] preferred over String for storage of password in Java
- What is I/O Filter and how do I use it in Java?
- Serialization and Deserialization in Java
- Understanding transient variables in Java
- What is Externalizable in Java?
- What is the purpose of serialization/deserialization in Java?
- What is the Difference between byte stream and Character streams
- How to append text to an existing file in Java
- How to convert InputStream object to a String in Java
- What is the difference between Reader and InputStream in Java
- Introduction to Java threads
- Synchronization in Java
- Static synchronization Vs non static synchronization in Java
- Deadlock in Java with Examples
- What is Daemon thread in Java
- Implement Runnable vs Extend Thread in Java
- What is the volatile keyword in Java
- What are the basic interfaces of Java Collections Framework
- Difference between ArrayList and Vector | Java
- What is the difference between ArrayList and LinkedList?
- What is the difference between List and Set in Java
- Difference between HashSet and HashMap in Java
- Difference between HashMap and Hashtable in Java?
- How does the hashCode() method of java works?
- Difference between capacity() and size() of Vector in Java
- What is a Java ClassNotFoundException?
- How to fix java.lang.UnsupportedClassVersionError