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. The curriculum of the Software Testing Training Course in Noida is regularly updated to incorporate the latest industry trends and technologies. Students can expect to learn about manual testing, automation testing, performance testing, and much more. The course also includes comprehensive training in widely used testing tools such as Selenium, JIRA, and TestNG. This equips graduates with the skills required to stand out in a competitive job market.

    ReplyDelete
  7. Are you seeking a Best Java Training Course in Noida with Placement Assistance that not only provides comprehensive learning but also ensures placement assistance? Look no further than APTRON Solutions. Renowned for its excellence in IT training, APTRON Solutions offers a cutting-edge Java course that equips you with the skills and knowledge necessary to excel in the competitive tech industry.

    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

Entity to DTO conversion in Java using Jackson

It's very common to have the DTO class for a given entity in any application. When persisting data, we use entity objects and when we need to provide the data to end user/application we use DTO class. Due to this we may need to have similar properties on DTO class as we have in our Entity class and to share the data we populate DTO objects using entity objects. To do this we may need to call getter on entity and then setter on DTO for the same data which increases number of code line. Also if number of DTOs are high then we need to write lot of code to just get and set the values or vice-versa. To overcome this problem we are going to use Jackson API and will see how to do it with minimal code only. Maven dependency <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> Entity class Below is