Singleton : Creational design pattern

Standard

Singleton design pattern is a concept and it comes only when it is necessary that one and only one instance of a particular class should be exists in the entire Java Virtual Machine. That means the main purpose of the singleton class is to control object creation, limiting the number of objects to only one.

It seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. Here we will learn about Singleton design pattern principles, different ways of implementation and some of the best practices for its usage.

Common Uses

  1. Singletons are often useful where we have to control the resources, such as database connections or sockets.
  2. Singleton pattern is used for logging, driver objects, caching and thread pool.
  3. Singleton design pattern is also used in other design patterns.
    For example Abstract FactoryBuilderPrototypeFacade
  4. Singleton design pattern is used in core java classes also.
    For example lang.Runtimejava.awt.Desktop, java.lang.System
  5. Derive the singleton class from an interface.
    This helps while doing unit testing (using Dependency Injection).

 

Implementation

To implement Singleton pattern, we have different approaches but all of them have following common concepts.

  1. Create a private static variable of that class & that is the only instance.
  2. Make constructor private, which restricts instantiation of the class from other classes.
  3. Create a public static method that returns the instance of the class & this is the global access point for outer world to get the instance of the singleton class.

Now, we will learn different approaches of singleton pattern implementation and the design concerns with the implementation.

 

  1. Eager initialization

This is the easiest method to create a singleton class. Here instance will be created when the class is loaded into the JVM. If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization.

public class SingletonExample {

  // Static member holds only one instance of the
  // SingletonExample class
  private static SingletonExample singletonInstance = new SingletonExample();

  // SingletonExample prevents any other class from instantiating
  private SingletonExample() {}

  // Providing Global point of access
  public static SingletonExample getSingletonInstance() {
     return singletonInstance;
  }
}

Overuse of Eager initialization may cause memory problems.

 

  1. Static block initialization
    Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
public class SingletonExample {

  // Static member holds only one instance of the
  // SingletonExample class
  private static SingletonExample singletonInstance;

  // SingletonExample prevents any other class from instantiating
  private SingletonExample() {}

  //static block initialization for exception handling
   static{
           try{
                     instance = new StaticBlockSingleton();
                     }catch(Exception e){
                              throw new RuntimeException(“Exception occured”);
                     }
              }

  // Providing Global point of access
  public static SingletonExample getSingletonInstance() {
     return singletonInstance;
  }
}

Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use.

 

  1. Lazy initialization
    Lazy initialization means that the instance will not create until required.
public class SingletonExample {

    private static SingletonExample singletonInstance;

    // private constructor to force use of
    // getInstance() to create Singleton object
    private Singleton() {}

    public static SingletonExample getInstance(){

        if (singletonInstance == null){
                    singletonInstance = new SingletonExample();
        }
        return singletonInstance;
    }
}

 

The main problem with above implementation is that it is not thread safe. It will works fine in case of single thread, but in multithreaded system it will break the general rules of singleton design pattern means multiple instance can be created from a singleton class Each instance on each thread can be created means multiple instance of a singleton calss in a single JVM.

 

Then how we make it thread safe?

The easiest way is to make the global access method synchronized, so that only one thread can execute this method at a time. 

public class SingletonExample{
          private static SingletonExample singletonInstance;

          // private constructor to force use of getInstance() to create Singleton object
          private Singleton() {}

          // Only one thread can execute this at a time
          public static synchronized SingletonExample getInstance(){
                    if (singletonInstance == null){
                                 singletonInstance = new SingletonExample();
          }
          return singletonInstance;
}

 

Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method. However if performance of getInstance() is not critical for your application this method provides a clean and simple solution.

To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

 

// Double Checked Locking based Java implementation of singleton design pattern
public class SingletonExample{

    private volatile static SingletonExample singletonInstance;

    private SingletonExample() {}

     public static SingletonExample getInstance(){
                    if (singletonInstance == null){
                                 // To make thread safe
                                 synchronized(SingletonExample.class){
                                           // check again as multiple threads can reach above step
                                          if (singletonInstance == null){
                                                 singletonInstance = new SingletonExample();
}
                                   }

                     }
                      return singletonInstance;
      }
}

 

We have declared “singletonInstance” variable volatile which ensures that multiple threads offer the “singletonInstance” variable correctly, when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time.

Advertisements

Spring boot : Read application.properties

Standard

Method 1

Environment represent current system configuration. Its provide getProperty method which return provided valued based on passed property name. It also support return Default Value if configuration return null value or configuration is not available. Here is example of spring boot read application properties using Environment.

  • import org.springframework.beans.factory.annotation.Autowired;
  • import org.springframework.core.env.Environment;
  • import org.springframework.stereotype.Service;
  • @Service
  • public class ApplicationService {
  • @Autowired
  • private Environment environment;
  • public void printProperties(){
  • System.out.println(environment.getProperty(“app.domain”)); // It will return properties value from application.properties file, If key will not available than it will return null
  • System.out.println(environment.getProperty(“app.subdomain”));
  • System.out.println(environment.getProperty(“app.rootsubdomain”,“Default Value”)); // If value is null than return default value
  • }
  • }

Method 2

@Value(“${propertyName[:DEFAULT VALUE]}”) is syntax to read properties from application.properties file. here is example of read application properties using @Value annotation.

 

  • import org.springframework.beans.factory.annotation.Value;
  • import org.springframework.stereotype.Service;
  • /**
  • * Created by Java Developer Zone on 26-08-2017.
  • */
  • @Service
  • public class ApplicationService {
  • @Value(“${app.domain}”)
  • private String appDomain;
  • @Value(“${app.subdomain}”)
  • private String appSubdomain;
  • @Value(“${app.rootsubdomain:Default value}”) // This properties is not available so it will return default value
  • private String rootsubdomain;
  • public void printProperties(){
  • System.out.println(“Domain: “+appDomain); // It will return properties value from application.properties file, If key will not available than it will return null
  • System.out.println(“Sub Domain: “+appSubdomain);
  • System.out.println(“Root Domain: “+rootsubdomain);
  • }
  • }

Reference : Spring Boot Reference Guide

Install adobe reader in ubuntu

Standard

1. Open the terminal and run the following command:
sudo apt-get install gtk2-engines-murrine:i386 libcanberra-gtk-module:i386 libatk-adaptor:i386 libgail-common:i386

2. Now install Adobe reader using the following commands:
sudo add-apt-repository “deb http://archive.canonical.com/ precise partner”
sudo apt-get update
sudo apt-get install adobereader-enu

3.After installation you need to remove the precise repository using the following commands:
sudo add-apt-repository -r “deb http://archive.canonical.com/ precise partner”
sudo apt-get update

4.If you want to read all PDF files using adobe acrobat do the following changes
Edit the /etc/gnome/defaults.list file
sudo gedit /etc/gnome/defaults.list

5.Change the following line
application/pdf=evince.desktop
to
application/pdf=acroread.desktop

6.Also add the following lines in the end
application/fdf=acroread.desktop
application/xdp=acroread.desktop
application/xfdf=acroread.desktop
application/pdx=acroread.desktop

7.Save and exit the file.Now you need to restart nautilus using the following command
nautilus -q

Configure Gmail SMTP server in Liferay

Standard

1. Go to Control Panel > Portal Settings
2. Enter “gmail.com” on Mail Domain (Required)
3. Save settings
Portal Settings - Liferay
4. Go to Control Panel > Server Administration > Mail

5. Now set the following settings below
Incoming POP Server : pop.gmail.com
Incoming Port : 995
Use a Secure Network Connection : yes
User Name : yourmail@gmail.com
Password : Your gmail Password
Outgoing SMTP Server : smtp.gmail.com
Outgoing Port  : 465
Use a Secure Network Connection  : yes
User Name : yourmail@gmail.com
Password : Your gmail Password
Manually specify additional JavaMail properties to override the above configuration:
mail.smtp.socketFactory.port: 465
mail.smtp.socketFactory.class:javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback:false
mail.smtp.auth: true
liferay-gmail configuration

6. Sign-in your gmail account
7. Enable DisplayUnlockCaptcha feature by clicking on  Enable DisplayUnlockCaptcha
8. Enable AllowLessSecureApps feature by clicking on Turn on “Allow less secure apps”
9. Disable TwoStepVerification feature by clicking on Turn off “2 Steps Verification”

Setup MySQL as Datasource for OFBiz

Standard

Derby is the default database of ofbiz. Now we migrate our database to MySQL from derby.
1. Before you start migrating check your installed MySQL version & download the supported version of mysql-connector.jar
2. Place the mysql-connector.jar to <ofbiz-dir>/framework/entity/lib/jdbc
MysqlConnector
3. Create 3 database [Ex. ofbiz, ofbizolap, ofbiztenant]
4. Open entityengine.xml file from <ofbiz-dir>/framework/entity/config/
5. Edit as follows,