Skip to main content

Singleton class in java

What is Singleton class

Singleton is a design technique which gaurantees that there will be only instance of a class globally. Such classes are required when we need to create some objects which are memory/ resource extensive and we can't afford many such objects.

Using singleton We can maintain single object per JVM per classloader. Classloader could be different in different hierarchy and in such case we may have more than one instances of singleton but we can avoid it by loading it at appropriate classloader. For example in an ear application there could be multiple web modules and each one of them will have their own singleton instance. Sometimes it may be a need but sometimes it could be a flaw which can be resolved by loading it either at ear level or web module level as per requirement.

Implementing singleton class

There are two different ways to implement singleton in java.
  1. Using singleton design pattern

  2. In this pattern we can create singleton either using lazy loading or using eager loading.

    In lazy loading, we create the instance when we actually need it. But implementation is little tricky and we need to handle thread safety. Below is the example of lazy loading implementation.

      public class MySingleton{
          private static MySingleton instance = null;
          
          private MySingleton(){}
          
          public static MySingleton getInstance(){
              if(instance==null){
              	synchronised(MySingleton.class){
                	if(instance==null){
                  		instance=MySingleton();
                    }
                }
              }
              return instance;
          }
      }
      

    In eager loading, we create the instance as soon as class is loaded. Implementation is easy here and we don't need to worry about thread safety. But it creates the object whether we need it or notBelow is the example of lazy loading implementation.

      public class MySingleton{
          private static MySingleton instance = MySingleton();
          
          private MySingleton(){}
          
          public static MySingleton getInstance(){
    
               return instance;
          }
      
      }
      
  3. Using enum class

  4. Singleton creation is very easy using enums. Just create an enum class as given below. You can also create parameterized Enum instances by adding the relevant constructor.
      public enum MySingleton {
    	
    	instance;
    	
      }
      
    And then you can get the instance by just using below code.
    MySingleton i = MySingleton.instance;

Best approach to create singleton

You already saw here that you can create singleton either of the above approaches but there are some differences between them.

With singleton design pattern class creation need to handle synchronization. Also there is a chance that it can be serialized/ deserialized or class variables accessor can be modified using reflection which will destroy the singlton.

In my opinion using Enum for singleton will be the better option as it will automatically handle the above problems.

Comments

  1. Thanks for sharing a really needed post that i am looking for , if anyone looking for best java institute in delhi so join with us visit our website : https://www.htsindia.com/java-training-courses or contact us : +91-9311002620

    ReplyDelete
  2. Thanks for sharing this informative post. It's really kind of content that I'm looking for a very helpful post by the way. If anyone looking for best Sas training institute in Delhi Contact Here-+91-9311002620 Or Visit our website https://www.htsindia.com/Courses/business-analytics/sas-training-institute-in-delhi

    ReplyDelete

  3. This is really a good source of information, I will often follow it to know more information and expand my knowledge, I think everyone should know it, thanksccna practice test

    ReplyDelete
  4. Thank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the SAS Training institute in Delhi, can contact 9311002620 or visit our website-
    Best SAS Training Institute in Delhi | Best SAS Training Institute in Noida (htsindia.com)

    ReplyDelete
  5. If you're looking to excel in the field of networking, CCNA Training in Noida at APTRON is your gateway to success. In this SEO-friendly article, we'll delve into why APTRON's CCNA training in Noida is the ideal choice for aspiring network professionals.

    ReplyDelete
  6. Welcome to the Beginner's Guide to Software Testing at APTRON, your gateway to understanding the fundamental concepts and practices of software testing. In today's technology-driven world, software quality and reliability are paramount, making software testing an indispensable part of the software development process.

    ReplyDelete
  7. At the heart of our success lies our dedicated team of experienced instructors. Our Cloud Computing Institute in Noida takes pride in its faculty, comprising seasoned professionals with real-world experience in cloud computing. Their insights, industry knowledge, and commitment to your success will empower you with practical skills and in-depth understanding.

    ReplyDelete

Post a Comment

Popular Posts

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to

Multiple data source with Spring boot, batch and cloud task

Here we will see how we can configure different datasource for application and batch. By default, Spring batch stores the job details and execution details in database. If separate data source is not configured for spring batch then it will use the available data source in your application if configured and create batch related tables there. Which may be the unwanted burden on application database and we would like to configure separate database for spring batch. To overcome this situation we will configure the different datasource for spring batch using in-memory database, since we don't want to store batch job details permanently. Other thing is the configuration of  spring cloud task in case of multiple datasource and it must point to the same data source which is pointed by spring batch. In below sections, we will se how to configure application, batch and cloud task related data sources. Application Data Source Define the data source in application properties or yml con

Integrated/Kerberos authentication using Spring boot and SPNEGO API

In this tutorial we will learn how to use Spring boot and SPNEGO API to implement the kerberos or integrated authentication. Kerberos is developed by Massachusetts Institute of Technology (MIT) which is used to authenticate between trusted services using KDC tickets. For example email client, HR portal or employee portal in a corporate network where employee doesn't need to provide their user id & password to access these application in the same domain. Once they are logged in to their machine, they can access such services/application with kerberos authentication. I am using MAC OS X to demonstrate the kerberos authentication. I have used the same machine to configure and run the application backed with kerberos authentication and my KDC database & application reside on the same machine. Setting up kerberos  First of all we need to setup kerberos where we will configure the database, create user principals, create policies and keytabs. We need to create our applicatio