MySQL:create database with charset utf-8

Standard

CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Advertisements

Install ps_mem in Ubuntu

Standard

ps_mem is a utility to accurately report the core memory usage for a program.
Github source: https://github.com/pixelb/ps_mem

  1. Download the .zip from the Github source or execute the command to download
    git clone https://github.com/pixelb/ps_mem.git
  2. After download complete go to the folder and ensure ps_mem.py (python script) file is available.
  3. Execute command below to move the file to ( /usr/local/sbin/ ) directory,
    sudo mv ps_mem.py /usr/local/sbin/
  4. Give permission
    sudo chmod 755 /usr/local/sbin/ps_mem.py 
  5. Execute command below to show your memory usage and enjoy !!
    sudo ps_mem.py

Create Symbolic Links in Ubuntu

Standard

The syntax for creating a symbolic link is,
sudo ln -s target destination
where,

  • target – The existing file/directory you would like to link TO.
  • destination – The file/folder to be created, copying the contents of the target. The LINK itself.

For more help see ln –help

Example:
sudo ln -s /home/imtiaz/eclipse/eclipse /home/imtiaz
This would create a symbolic link of eclipse launcher to my “home” directory.

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.

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