How to create immutable class in Java?

immutable class

Immutable Object
Once created its state can not be altered.
String is good example of Immutable class in Java which you use in your day-to-day programming.

Read: Why String is immutable in Java?

Most important benefit of immutable class is, It provides thread safety so you don't have to worry about its value getting changed in multi-threaded environment. Also immutable class with valid hashCode() and equals() method is good choice for Map key.

Points to be taken care while creating immutable class.

  • Class must be declared as final so it can not be extended. i.e public final class ClassName.
  • All variables/critical methods should be private so it can not be accessed outside of class. i.e private int x;.
  • Make all mutable variables final so it can not be changed after initialization.
    i.e private final int x;.
  • Initialize all variables via constructor only by performing deep copy. (follow example)
  • Do not provide setter methods for variables. i.e public void setX(int x) {this.x = x;}
  • Return cloned object/variable in getter method rather returning actual object. (follow example)

Source code (ImmutableClassLatLon.java)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Example of Immutable class in java.
 * @author javaQuery
 * @date 2019-12-10
 * @Github: https://github.com/javaquery/Examples
 */
public final class ImmutableClassLatLon {
    private final double latitude;
    private final double longitude;
    private final List<String> labels;

    /**
     * @param latitude
     * @param longitude
     * @param labels
     */
    public ImmutableClassLatLon(double latitude, double longitude, List<String> labels) {
        this.latitude = latitude;
        this.longitude = longitude;
        if(labels != null && !labels.isEmpty()){
            this.labels = new ArrayList<>(labels);
        }else{
            this.labels = null;
        }
    }

    /**
     * Will return new copy of List rather returning reference to current list.
     * @return
     */
    public List<String> getLabels() {
        return labels != null ? new ArrayList<>(labels) : null;
    }

    /**
     * Get new object of ImmutableClassLatLon with updated label.
     * @param label
     * @return ImmutableClassLatLon
     */
    public ImmutableClassLatLon addLabel(String label){
        List<String> temporary = new ArrayList<>();
        if(labels != null && !labels.isEmpty()){
            temporary.addAll(labels);
        }
        temporary.add(label);
        return new ImmutableClassLatLon(latitude, longitude, temporary);
    }

    public static void main(String[] args) {
        ImmutableClassLatLon classLatLon = new ImmutableClassLatLon(23.0225, 72.5714, Arrays.asList("India"));
        System.out.println("classLatLon address: " + classLatLon);

        System.out.println("\n- classLatLon getLabels and add label -");
        System.out.println("classLatLon labels before: " + classLatLon.getLabels());
        /* classLatLon.getLabels() will return new copy of List rather returning reference to current list */
        List<String> localLables = classLatLon.getLabels();
        localLables.add("Hindi");
        System.out.println("localLables: " + localLables);
        System.out.println("classLatLon labels after: " + classLatLon.getLabels());

        System.out.println("\n- add new label to classLatLon -");
        System.out.println("classLatLon add label before: " + classLatLon.getLabels());
        /* When new label is added it will return new object of ImmutableClassLatLon rather updating current object's list */
        ImmutableClassLatLon classLatLonNewLabel = classLatLon.addLabel("Asia");
        System.out.println("classLatLon add label after: " + classLatLon.getLabels());
        System.out.println("classLatLonNewLabel address: " + classLatLonNewLabel);
        System.out.println("classLatLonNewLabel labels: " + classLatLonNewLabel.getLabels());

    }
}
Output
As you can see after initialization of ImmutableClassLatLon@36baf30c, user can not change its state even if we provided operation on it.
classLatLon address: com.javaquery.core.immutable.ImmutableClassLatLon@36baf30c

- classLatLon getLabels and add label -
classLatLon labels before: [India]
localLables: [India, Hindi]
classLatLon labels after: [India]

- add new label to classLatLon -
classLatLon add label before: [India]
classLatLon add label after: [India]
classLatLonNewLabel address: com.javaquery.core.immutable.ImmutableClassLatLon@7a81197d
classLatLonNewLabel labels: [India, Asia]
Further Reading
What is the difference between final and effectively final?
How HashMap works internally in Java?
How LinkedHashMap works internally in Java?

How LinkedHashMap works internally in Java?

LinkedHashMap implemented using the HashMap. So before we begin to understand How LinkedHashMap works you should first read How HashMap works internally in Java?

We will understand part of code that defers from HashMap and supports LinkedHashMap implementation.

LinkedHasMap#Entry
Entry class in LinkedHashMap extends Node class of HashMap and contains two more variable before and after to hold the before and after references of Entry object.
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}
Now when you put(key, value) pair in LinkedHashMap, it creates new node object by calling newNode(..) method. In newNode(..) method linkNodeLast(LinkedHashMap.Entry<K,V> p) method is called which is responsible for pointing head and tail element in LinkedHashMap and also set reference of before and after objects.
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
    LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e);
    linkNodeLast(p);
    return p;
}

private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
    LinkedHashMap.Entry<K,V> last = tail;
    tail = p;
    if (last == null)
        head = p;
    else {
        p.before = last;
        last.after = p;
    }
}
Following image shows graphical representation of How LinkedHashMap works internally.


Lets understand LinkedHashMap implementation using real Java Program to make everything clear.

Source code (LinkedHashMapExample.java)
Note: Check value of before, after and next to understand example.
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LinkedHashMap Example.
 * @author javaQuery
 * @date 2019-11-29
 * @Github: https://github.com/javaquery/Examples
 */
public class LinkedHashMapExample {
    public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<>();

        /* Check value of before, after and next to understand example */
        map.put("AaAaAa", "JJJ");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = null]
         */

        map.put("xyz", "KKK");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = EntryObject2]
         *
         * bucket-index: 11
         * EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = null]
         */

        /* since hashcode of 'AaAaBB' is same as 'AaAaAa' so it be added at 2nd index in bucket */
        map.put("AaAaBB", "LLL");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * [
         *  EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = EntryObject3, after = EntryObject2]
         *  EntryObject3 [before = EntryObject2, hash = 123, key = AaAaBB, value = LLL, next = null, after = null]
         * ]
         *
         * bucket-index: 11
         * EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = EntryObject3]
         */
    }
}
Above program can be graphically represented as follows.


References
How HashMap works internally in Java?
Popular Map interview questions in Java

Popular Map interview questions in Java

Question: Why Map interface does not extends Collection interface?
Answer: Map is (key, value) pair not a collection of one type of values so it does not extends Collection interface. Collection interface accept single object via add(E e) but Map interface requires key, value pair in method put(K key, V value)

Question: Does Map accept `null` as key?
Answer: HashMap and LinkedHashMap accepts null key but TreeMap will throws NullPointerException. HashMap stores null key at 0th index in bucket.

Question: Does Map accept `null` values?
Answer: You can have n null values.

Question: What is the initial capacity of HashMap?
Answer: 16. DEFAULT_INITIAL_CAPACITY = (1 << 4)

Question: What is the maximum capacity of HashMap?
Answer: 1073741824. MAXIMUM_CAPACITY = ( 1 << 30)

Question: Does HashMap maintain insertion order?
Answer: No

Question: Is HashMap synchronized?
Question: Is HashMap thread-safe?
Answer: No

Question: How to synchronize Map?
Answer: Using Collections.synchronizedMap(map), best practice Map m = Collections.synchronizedMap(new HashMap(...));

Question: How to avoid concurrent modification exception?
Answer: Synchronize Map using Map m = Collections.synchronizedMap(new HashMap(...)); or Map n = new ConcurrentHashMap();

Question: How HashMap works internally in Java?
Answer: To understand How HashMap works internally read the article https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html

Question: What happens when you put same key again in HashMap?
Answer: When you put(existing-key, value) in HashMap, it will replace old value with new value. And returns old value.
Map<String, String&gt; map = new HashMap<&gt;();
map.put("a", "x");
String oldValue = map.put("a", "y");
System.out.println(oldValue);
//output: x

Question: Can we store duplicate key in HashMap?
Answer: No

Question: Can we store duplicate value in HashMap?
Answer: Yes.

Question: What is Hash code/key collision?
Answer: When two same or different hash code of key generates same index of bucket location by performing bitwise AND is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).

For example "AaAaAa".hashCode() and "AaAaBB".hashCode() generates same hash code.

Question: How HashMap handles Hash code/key collision?
Question: What will happens if two objects have same hash code?
Answer: It forms linked list at bucket location.

Question: Why String, Integer and other wrapper classes are good choice for HashMap key?
Answer: String, Integer and other wrapper classes are immutable so its best choice to use it as key. Why String is immutable in Java?

Question: Can we use mutable key in HashMap?
Answer: Yes, You can use mutable key but its not good choice because it'll fail to retrieve correct value in get(key).

Question: Can we use our own custom object/class as key in HashMap?
Answer: Yes, You can use your custom object as key in HashMap but its necessary to consider immutability of that object and also implementing hashCode() and equals() method in your class.

Question: How HashMap is improved in Java 8?
Answer: Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold TREEIFY_THRESHOLD = 8 and MIN_TREEIFY_CAPACITY = 64 then it uses TreeNode to store Entry object to improve HashMap get performance.
Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?

Question: Which tree stucture is used in Java 8 to improve performance of HashMap?
Answer: red-black tree structure is used to improce performance of HashMap.

Question: How LinkedHashMap works internally in Java?
Answer: To understand How LinkedHashMap works internally read the article https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html

How HashMap works internally in Java?

HashMap is one of the implementation of java.util.Map interface. We will understand how it internally stores (put) and retrieve (get) values. HashMap uses array known as bucket/table to store (key, value) pair.

This is one of the popular question in Java Interviews, lets understand how it works.

Instantiation: How to create HashMap object?
There are 3 different ways you instantiate HashMap

  1. new HashMap() - It will create HashMap with default capacity of 16 and default load factor 0.75f.
  2. new HashMap(int initialCapacity) - You can provide the initial capacity of HashMap and default load factor 0.75f is used.
  3. new HashMap(int initialCapacity, float loadFactor) - You can provide both initial capacity and load factor.
Note: We will consider HashMap with default capacity and load factor for explanation of this article.

Understanding implementation of HashMap
I extracted Node class (inner class) from HashMap which implements sub-interface Entry of Map interface. Node class plays important role in implementation of HashMap. Every (key, value) pair in HashMap will be stored as Entry object using Node class implementation.

Node class holds - hash code of key, key, value and `next` is used to store next element (node) reference in case of hash code/key collision. We'll understand hash code/key collision later in this article.
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash; // hash code of key
    final K key; // the key
    V value; // the value to put
    Node<K,V> next; // next element(node) in case of hash code/key collision 

    Node(int hash, K key, V value, Node<K,V> next) {...}
    ...
    ...
}

What happens when you put(K key, V value) in HashMap?
When you put (key, value) pair in HashMap, it generates hash of key by calling hashCode() method of key and follows these steps...

  • put#1.1: Create the bucket (array) of Node<K, V>[] with default capacity or given capacity if not initialized. 
    • In case of bucket (array) is full then it increases capacity by twice the current capacity and transfer all data to new bucket (array). (i.e default capacity [16] > [32] > [64] ...)
  • put#1.2: Now it generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key
    /**
     * i = index to store (key, pair) in bucket (array)
     * n = size of bucket (array)
     * hash = hash code of key
     */
    int i = (n - 1) & hash;
    
  • put#1.3: Fetch node (element) from bucket using generated location (index).
    • put#1.3.1: no element found - insert given key, pair in form of Node object (Entry object).
    • put#1.3.2: element found at that location (index) - its the case of Hash code/key collision.
      • put#1.3.2.1: Now it'll compare key of existing node (element) with newly given key. If both the keys are same then it'll replace current Node's value with new value.
      • put#1.3.2.2: If both the keys are different then it forms linked list at the bucket location (index). Current node's next variable will be assigned to reference of newly given Node (key, value). 


What happens when you get(Object key) in HashMap?
When you try to get value using key, it generates hash of key by calling hashCode() method of key and follows these steps...

  • get#1.1: Generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key.
  • get#1.2: Find the Entry(Node) object from that bucket index.
    • get#1.2.1: No Entry object found - returns null.
    • get#1.2.2: Entry object found from bucket - It will compare provided hash of key, key and calls equals() method of key with Entry object found from bucket. 
      • get#1.2.2.1: If everything matched then it returns the Entry object. 
      • get#1.2.2.2: If not matched then it check linked list formed at that bucket location (has `next` element) then do the same check as in get#1.2.2 until it find the correct Entry object from linked list.
Now lets discuss question can be asked in interview related to implementation.

What is the initial capcity and load factor of HashMap?
Initial capacity of HashMap is 16 and load factor is 0.75f.

How HashMap stores data in bucket (array/table)?
Its important to remember that HashMap stores not just hash code of key in Array. It stores hash code, key, value and `next` as Entry object in Array.

What is Hash code/key collision?
When two same or different hash code of key generates same index of bucket location by performing bitwise AND is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).

For example "AaAaAa".hashCode() and "AaAaBB".hashCode() generates same hash code.

How HashMap handles Hash code/key collision?
What will happend if two objects have same hash code?
It forms linked list at bucket location.

How HashMap will retrieve value when two keys have same hash code?
Linked list formed at bucket location when two keys have same hash code so it'll travese through all linked list node until it find the correct key and equals method of key retruns true. Read get1.2.2 for complete understanding.

Where does HashMap stores null key?
null key will be stored at 0th index of bucket.

Why String, Integer and other wrapper classesare good choice for HashMap key?
String, Integer and other wrapper classes are immutable so its best choice to use it as key. Why String is immutable in Java?

Can we use mutable key in HashMap?
Yes, You can use mutable key but its not good choice because it'll fail to retrive correct value in get(key).

Can we use our own custom object as key in HashMap?
Yes, You can use your custom object as key in HashMap but its necessary to consider immutablity of that object and also implementing hashCode() and equals() method in your class.

How HashMap is improved in Java 8?
Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold TREEIFY_THRESHOLD = 8 and MIN_TREEIFY_CAPACITY = 64 then it uses TreeNode to store Entry object to improve HashMap get performance.
Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?

Which tree stucture is used in Java 8 to improve performance of HashMap?
red-black tree structure is used to improce performance of HashMap.

References
Popular Map interview questions in Java
How LinkedHashMap works internally in Java?

What is Abstract class in Java and popular interview questions?

What is Abstract Class?
An abstract class is a class that is incomplete, or to be considered incomplete.

You can declare abstract methods for which non abstract subclass has to provide implementation or it'll give compile-time error. "Methods that are declared but not yet implemented."

Also you can provide method implementation in abstract class itself. It can be used from subclass. You can override these method in its subclass.

Source code (Mobile.java)
import java.util.Date;
public abstract class Mobile {

    /**
     * Sub class has to provide implementation for method `call()`
     */ 
    public abstract void call();

    /**
     * Sub class has to provide implementation for method `sms()`
     */ 
    public abstract void sms();

    /**
     * We've provided implementation for current time.
     */
    public Date currentTime(){
     return new Date();
    }
}
Source code (SmartMobile.java)
public class SmartMobile extends Mobile{
 
    public void call(){
     // provide implementation
    }

    public void sms(){
     // provide implementation
    }
}
Source code (Main.java)
public class Main(){
    public static void main(String[] args){
     /** You can not instantiate abstract class. 
      * Following line will cause Compile-Time error 
      */
     // Mobile mobile = new Mobile();

     Mobile smartMobile = new SmartMobile();
    }
}

Now lets discuss behavior of abstract class via question-answer. These are the popular abstract class interview questions .

Question: Can we instantiate abstract class?
Answer: No. We can not instantiate abstract class. Its restricted by Java.

Question: Why does abstract class have constructor if we can not instantiate? 
Answer: Constructor in abstract class used to initialize properties/fields of abstract class via not abstract sub-class.

Question: When constructor of abstract class called?
Answer: When sub-class instantiated, constructor of abstract class is called.

Question: Can we mark constructor as abstract?
Answer: No

Question: Is it compulsory for abstract class to have at least one abstract method?
Answer: No its not compulsory. You can create abstract class with or without abstract methods.

Question: Can we declare abstract method as private? 
Answer: No. If abstract method is private then its not visible/accessible in its sub-class so it can not provide its implementation. However you can make abstract method protected.

Question: Why final and abstract can not be used at a time? 
Answer: When class or method marked with final means value or implementation provided and you don't want it to be changed while abstract means implementation asked to provide.

Simply it contradicts with each other.

Question: Can we declare abstract class or method as static?
Answer: No. static can be called without creating object and it contains implementation or value. abstract means implementation asked to provide. Its same as final.

Simply it contradicts with each other.

Question: Can we declare inner class as abstract?
Answer: Yes

Question: Can abstract method include throws in its declaration?
Answer: Yes

Question: Can we mark abstract method as synchronized?
Answer: No. However sub-class which override the method can be synchronized.
public abstract class Demo{
    public abstract void test();
}

public class DemoImpl extends Demo{
    @Override
    public synchronized void test(){
        //implementation
    }
}

Question: Can we use abstract class as member of another abstract class?
Answer: Yes. Its same as declaring other class as member(variable).

Reference
Difference between Abstract class and Interface in Java

How to run MySQL Server in docker?

MySQL in Docker

In my previous article we understood Why Docker and What is Docker? Now lets see how you launch MySQL in Docker.

Prerequisite
Docker must be installed in your local system.

Step 1: Open terminal in root mode. Launch MySQL by following command. It'll download MySQL DockerImage if not available and then start it.
root@vicky:/home/vicky# docker run --name localmysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql
Unable to find image 'mysql:latest' locally
latest: Pulling from library/mysql
6ae821421a7d: Pull complete 
a9e976e3aa6d: Pull complete 
e3735e44a020: Pull complete 
bfd564e9483f: Pull complete 
df705f26e488: Pull complete 
0c5547f73d62: Pull complete 
f437382cf8a1: Pull complete 
b8e2d50f1513: Pull complete 
e2e3c9928180: Pull complete 
b60db6d282cd: Pull complete 
1d32deab69c6: Pull complete 
408a40cd2e9c: Pull complete 
Digest: sha256:a571337738c9205427c80748e165eca88edc5a1157f8b8d545fa127fc3e29269
Status: Downloaded newer image for mysql:latest
89911662a4793d0468427919d395535e05a3b3004aeb8173cd4d9eaede30fa3a
Step 2: Verify MySQL is running or not by executing following command.
root@vicky:/home/vicky# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
89911662a479        mysql               "docker-entrypoint..."   6 minutes ago       Up 6 minutes        0.0.0.0:3306->3306/tcp, 33060/tcp   localmysql
Step 3: Enter into Docker MySQL app by executing following command.
root@vicky:/home/vicky# docker exec -ti localmysql bash
Step 4: You are into MySQL app. You can now connect and execute to MySQL commands on it.
root@89911662a479:/# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.15 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> ALTER USER 'root' IDENTIFIED WITH mysql_native_password BY 'root';
Query OK, 0 rows affected (0.05 sec)

mysql> CREATE DATABASE javaquery;
Query OK, 1 row affected (0.08 sec)

mysql> use javaquery;
Database changed

mysql> CREATE TABLE demo(id int, name varchar(100), email varchar(250));
Query OK, 0 rows affected (0.19 sec)

mysql> INSERT INTO demo(id, name, email) values(1, 'Vicky Thakor', 'vicky.thakor@javaquery.com');
Query OK, 1 row affected (0.05 sec)

mysql> SELECT * FROM demo;
+------+--------------+----------------------------+
| id   | name         | email                      |
+------+--------------+----------------------------+
|    1 | Vicky Thakor | vicky.thakor@javaquery.com |
+------+--------------+----------------------------+
1 row in set (0.00 sec)

mysql> exit
Bye
Step 5: Exit from container
root@89911662a479:/# exit
exit
Step 6: Stop MySQL container
root@vicky:/home/vicky# docker container stop localmysql
localmysql
Step 7: Remove MySQL container from docker engine.
root@vicky:/home/vicky# docker container rm localmysql
localmysql
Step 8: List docker images.
root@vicky:/home/vicky# docker images -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               latest              81f094a7e4cc        47 hours ago        477MB
Step 9: Remove MySQL completely from Docker.
root@vicky:/home/vicky# docker rmi 81f094a7e4cc
Untagged: mysql:latest
Untagged: mysql@sha256:a571337738c9205427c80748e165eca88edc5a1157f8b8d545fa127fc3e29269
Deleted: sha256:81f094a7e4ccc963fde3762e86625af76b6339924bf13f1b7bd3c51dbcfda988
Deleted: sha256:77dac193858f3954c3997272aabbad794166770b735ea18c313cd920c6f9ae56
Deleted: sha256:29c7593e2c24df6b8a0c73c4445dce420a41801bb28f1e207c32d7771dfb2585
Deleted: sha256:5b0034d0389c5476c01ad2217fc3eddfcceb7fb71489fa266aac13c28b973bb5
Deleted: sha256:a8380edd959f5f457dfaff93b58bd9926cd7226fc7cfade052459bcaecf5404b
Deleted: sha256:75082d1a98ce7ef9eb053ed89644e09c38b4ebd6c964ec3eb050c637480a2874
Deleted: sha256:afa9c09812bcbc0960c0db6d5c1b3af6286097935e4aa46153b4538ad7082e4f
Deleted: sha256:7d3a170fc2a4187c57e941e4f37913add9034ac7e44f658630d38bc617b673b9
Deleted: sha256:1414c04de349b69ee9d1a593d766a275b92b1a01e4c440092ccde60b1ff8e5d9
Deleted: sha256:bcf08b24b02cc14c6a934d7279031a3f50bc903d903a2731db48b8cb6a924300
Deleted: sha256:81b6eebc1d362d1ca2a888172e315c4e482e0e888e4de4caef3f9e29a3339b78
Deleted: sha256:2c5c6956c8c5752b2034f6ab742040b574d9e3598fbd0684d361c8fc9ccb3554
Deleted: sha256:0a07e81f5da36e4cd6c89d9bc3af643345e56bb2ed74cc8772e42ec0d393aee3

Why Docker and What is Docker?

docker logo

Why Docker?
As a developer, Have you ever run into situations like...

  • Code is working in local system, ain't working on production/staging server.
  • Software(apache, php, etc...) upgrade on production/staging server crashed your code.
  • Require separate environment of your website/server to test newly developed feature.
All these problems of Software Development Life Cycle (SDLC) can be solved by docker. Now lets see...

What is Docker?
Docker is like virtual machine but unlike virtual machine, docker don't need separate Operating System on top of Host Operating System. Docker uses Host Operating System directly via Docker Engine to run applications.

Docker Containers vs Virtual Machines

How Software Development Life Cycle (SDLC) problems can be solved?
Using DockerFile, write your application specific environment to run.

What is DockerFile?
File contains environment specific configuration like: for development, for testing, for production, for release_v2.3.1, etc... This can be further drilled down as per your micro-services like...

  • dev-inventory-ui-php
  • dev-inventory-backend-java
  • dev-salesorder-ui-react
  • dev-salesorder-backend-spring

DockerFile
Sample docker file. No extension is required for this file.
FROM openjdk:8-jre
VOLUME /tmp
ADD your-app-main-1.0.jar destination-file-docker-app.jar
ENV JAVA_OPTS=""
ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /destination-file-docker-app.jar
Docker in action
On local system you developed your application with Java version 8 now specify same version in DockerFile. Image built/created from this DockerFile will run Java version 8 in Container. So application will work as expected.

Now say if you upgrade your code for Java version 9. All you need to do is just update your DockerFile's Java version to 9. Docker will check that Java version 9 is needed and not available so it'll download Java version 9 and then run your application.

Lets say something goes wrong then you can launch container from your previous DockerImage of Java version 8. And you application is downgraded, no need to uninstall Java version 9 or any other software you added with new DockerFile.

By just writing DockerFile you can control your application's execution environment from local to development and development to production. You can also create multiple DockerFile for different environments as per your requirements.

  • Code execution will be same as local for production server.
  • This way you don't need to worry about upgrading/downgrading your server's environment.
  • Also same DockerImage can be used to launch new service. Docker will download all required software on server that are mentioned DockerFile. No overhead of configuring server for launching new service.

Advantages of Docker

  • Light weight compare to virtual machine.
  • Same DockerImage can run on local, Kubernetes, Amazon Web Service, Google Cloud, Microsoft Azure or any other cloud platform without changing anything in DockerFile.
  • Quickly start your application in Docker.

Other References:
How to run MySQL Server in docker?