Monday, February 29, 2016

Java Exchanger

Introduction to Java Exchanger

Java Exchanger class is a synchronization point where threads can swap elements. In other words, Exchanger provides two way mechanism to exchange objects between threads. So now you can give your object and take his objects between pairs. It is some sort of bidirectional form of SynchronousQueue.

It is available from Java 1.5 however it is not very much known class to many Java developer.


Benefits of Java Exchanger

Passing data between threads in java is possible through Exchanger class. It solves the purpose of the problem of bidirectional exchange of objects.


Real Time Example / Use case

In Juice Factory, the juice is first extracted from fruits and stored in a large container, which is being sent for individual Packaging. Considering the above real time example / use case, JuiceExtraction system and Packaging System are the individual independent threads which can pair to exchange the Juice Container. Here the exchange item is the container. During pairing, JuiceExtraction container will pass filled-up container and receive the empty container. 

Here is the code sample for the above real time use case:

import java.util.concurrent.Exchanger;

public class JuiceFactory {
Exchanger<JuiceFactory.Container> exchanger = new Exchanger<JuiceFactory.Container>();

class JuiceExtraction implements Runnable{
Container currentContainer;
public JuiceExtraction(Container c){
this.currentContainer = c;
}
@Override
public void run() {
try {
while(currentContainer != null) {
// Extract juice and fill inside container
int result = currentContainer.fill(20);
if(result > 0) { 
// Container capacity is full, pass this container to Packaging
// system through Exchanger.

// wait till get a free container from Packaging system
currentContainer = exchanger.exchange(currentContainer); 


}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}


class Packaging implements Runnable{
Container currentContainer;
public Packaging(Container c){
this.currentContainer = c;
}

@Override
public void run() {
try {
while(currentContainer != null) {
// Takeout juice for packaging in bottle
int result = currentContainer.takeOut(25);
if(result > 0) {
// Container is empty. Pass this empty container to Juice extraction
// system and take another full container for packaging
currentContainer = exchanger.exchange(currentContainer);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}

class Container {
int capacity = 100;
int currentFillup = 0;

public Container (int initialVolume) {
currentFillup = initialVolume;
}
public int fill(int volume) {
if(currentFillup+volume > capacity) {
volume = volume - (capacity - currentFillup);
currentFillup = capacity;
return volume;
} else {
currentFillup+=volume;
return 0;
}
}

public int takeOut(int volume) {
if(currentFillup - volume < 0) {
volume = volume - (volume - currentFillup);
currentFillup = 0;
return volume ;
} else {
currentFillup-=volume;
return 0;
}
}
}

void start() {
new Thread (new JuiceExtraction(new Container(0))).start();
new Thread (new Packaging(new Container(100))).start();
}
}



Other Ideas:
Through Exchanger, we can also address Producer Consumer Problem Statement besides the areas where we need to exchange the objects between threads

If there is an application where it is required to be both one directional exchange and bi-directional based on certain criteria, we can use Exchanger as a one directional exchange (only give and receive null) and also bi-directional (both give and take).



Java SynchronousQueue (Synchronous Queue) Example

Java SynchronousQueue class is the only collection object which does not have any internal memory capacity. That's the beauty of this collection class and thus many fellow use to ask this in interview question about which Java collection class has no memory capacity? (Answer)

Now you might be wondering if it has no memory capacity, not even of one, then how come this collection framework is even working and how can anyone use it?

First of all, Synchronous Queue comes under the class of Blocking Queue i.e. it has all the features of Blocking Queue
Hence it works by putting the insert operation thread to wait for remove operation by another thread. In other words, the thread inserting element to Synchronous Queue gets blocked till another thread takes the element out and vice-versa. That means any thread tries to take out the element will get blocked if there is no another thread to put the element into the queue. So the thread which tries to put the element (and gets blocked until there is no taker) keeps hold of the element on its behalf and thus the queue size is always zero (no memory capacity of its own).

Real Time Example:
The best way to understand SynchronousQueue  is the ping-pong game, where a person passes the ball to another. Consider there are many persons and many balls for this ping-pong game. So here each person holding the ball is passing it to another person and that another person is passing to someone else and it goes on. 
In the above example, each person is a separate thread and ball is an element and it passes via Synchronous Queue. It is quite worthy to note that while Person A is passing the ball to Person B, it doesnot put the ball into any basket (Synchronous queue here) but passes directly to person B and thus the queue doesn't need to hold that ball element. So with this way N persons holding N balls blocks until another N another persons receives it.

How SynchronousQueue works internally:

When a thread put the element on Synchronous Queue, internally that thread goes to wait state on SynchronousQueue Object and when another thread take the element from the queue, it internally calls notify to SynchronousQueue Object leading to one waiting thread thread to wake up. You can also think Synchronous Queue as advanced way for Object wait() and notify() method. SynchronousQueue Object smartly uses Object's monitor lock feature to achieve this.

Thursday, February 18, 2016

Docker Interview Questions and Answers - Part I

Originally written by me in another blog at Docker Interview Questions and Answers and reproduced here for larger audience.

What is Docker

Docker is a platform to run each application isolated and securely. Internally it achieves it by using kernel containerization feature.

What is the advantage of Docker over hypervisors?

Docker is light weight and more efficient in terms of resource uses because it uses the host underlying kernel rather than creating its own hypervisor. 

What is Docker Image?

Docker Image is the source of the docker container. In other words, docker images are used to create containers. It is possible create multiple isolated containers from a single image.

What is Docker Container?

Docker Container is the instantiation of docker image. In other words, it is the run time instance of images. Images are set of files whereas containers is the one who run the image inside isolated.

Difference between Docker Image and container?

Docker container is the runtime instance of docker image.
Docker Image doesnot have a state and its state never changes as it is just set of files whereas docker container has its execution state.


Update: The second series of Docker Interview Questions is out.  Here is the link: Docker Interview Questions - Part II.

>>>>>> Docker Interview Questions - Part II

Java Equals Hashcode Contract Example

This the one of the most common question we used to face during Core Java interview, however its understanding is bit tricky. I will rather take unique approach to make the understanding simple.

So, what is the contract between hashcode and equals to be used as a key to HashMap / HashSet?

Java specification says that if you want to use any object as key to a hashmap or hashset or any other hashing, the contract is that
If two objects are equal according to the equals method, then its hashCode method on each of the two objects must return the same integer result.

Why so?

To understand why this contract even come into picture, we need to understand how hashmap works. Usually in best possible scenario, the time complexity to retrieve an object from hashmap is o(1). In other words, if you ask to retrieve an object by providing key from a map of millions, it just know where exactly it is and goes directly to that object and fetch it without iterating other objects. Thats the beauty of hashing technique.

Hashing Technique:

To understand hashing technique in simple terms, consider you have written a letter to me to be delivered.
Does the postman passes goes to each person and ask his name to find me?
Definitely not. He sends your post to the pincode and then it searches among the pincode. Since in best possible scenario, there is only one person per pincode, the letter reaches to me directly. This the way hashing technique works.
When you store an object to an hashmap, its stores on the key hashcode (also known as bucket). So, while retrieving in one shot, it requires the key hashcode again and thats why it is required to have same hashcode integer result every time. If it is going to give different hashcode, HashMap stores element on different code/bucket and trying to retrieve from different code/bucket, hence unable to retrieve object even-if it is present in hashmap on different bucket / hashcode / pincode.

Java Interview Questions on Atomic variables

Here are the list of 5 good questions on Volatile and Synchronized keywords in Java:

1. What is Atomic variables and its significance:

Atomic variables performs atomic operation on its object. In other words, it operation will happen completely or will not happen at all, and no one can interrupt its operation in between. With its introduction in Java 1.5, it is being widely used in multi-thread environment without any synchronization.

2. Is Atomic variable more faster or variable through synchronized code?

For read access, it does not matter whether it is atomic or non-atomic, synchronized or non-synchronized. For write access, atomic variable does not require lock to write because all update to variable happens atomic (either happened or not happened completely) For eg: suppose you want to do i++ in a multi-threaded application and multiple threads can call this, you need to synchronized i++ call (as it is set to 3 registry levels call and you know it can be context switch at any point of registry level calls even in between) to avoid dirty reads and inconsistent write. Atomic variable has just 1 registry level calls.

3. What is the disadvantage of Atomic variables as compared to its primitive type?

All Objects in java requires more care by the programmer to avoid memory consistency errors, doesnt matter whether it is Atomic or not. While the siblings of Atomic variable can be primitive and not object, it doesn't falls into object category and hence not required to take care of memory consistency error The reason why every object requires to avoid memory consistency errors in multi-threaded application is because each thread stack caches the copy of object locally on thread stack (Runtime optimization) might result into not in sync with actual copy of heap if it gets modified by another thread (even in the same code but different thread stack). One solution to avoid is to use volatile for that object which can be changed by another thread frequently. Also the local copy tries to in sync with heap copy very fast but problem occurs if your thread access it more faster than sync happens.

4. How Atomic variables are implemented internally or how atomic variables achieves atomicity?

With the introduction of additional register being added to cpu, atomic variables harness it to achieve atomicity. Since its just 1 cpu register call, it cannot be interrupted in between.

5. What are the atomic variable classes in java?

There are only two classes: AtomicInteger and AtomicLong. There is no atomic level classes for other primitives like double, float etc.

Difference between String, String Buffer and String Builder

In Java, these are the difference between String, String Builder and String Buffer:

String String Buffer String Builder
Immutable (cannot be changed after creation) Mutable (can be changed after creation) Mutable (can be changed after creation)
Thread Safe (Can be used across threads) Thread Safe (Can be used across threads) Not thread safe
Performance is good Performance is slow due to synchronized overhead Performance is good
'+' operation can be used in String to add two strings '+' operation is not allowed '+' operation is not allowed
Stored in constant String pool Stored in Heap area of memory Stored in Heap area of memory


Spring boot Interview Questions and Answers

What is Spring Boot?

Spring boot is the solution for creating standalone and production grade Spring application with very little Spring configuration.

Explain some features of Spring Boot?

Here are some features of Spring Boot:
  • It embeds web-application like Tomcat or Jetty directly
  • Comes with various already available maven's POM file to do minimal build creation code.
  • Automatically configure Spring
  • Provides inbuilt health-check feature
  • Provides inbuilt 'metrics' feature

What is the advantage of Spring Boot?

Following are the advantages of using Spring Boot:
  • Reduces lots of development time by providing boilerplate Java code and configuration
  • Easy to integrate with Spring ORM, Spring Security, Spring JDBC etc
  • Provides various plugins to develop, build and unit test Spring Boot applications with minimum effort.

Explain the purpose of spring-boot-starter-batch?

The purpose of spring-boot-starter-batch is to import all the dependency for the spring batch application. The advantage of it is that searching and configuring all the dependencies has become easier.

What are the template engines that Spring boot supports?

Spring boot supports the following template engines:
  • Groovy
  • FreeMarker
  • Mustache

What is the main disadvantage of Spring Boot?

Converting legacy Spring Framework application into Spring Boot application is not straight forward and is bit time consuming, which makes it difficult to port legacy Spring projects to Spring Boot application.

That's all for interview questions and answers on Spring Boot. Please provide your feedback in comment section.

Sunday, February 14, 2016

Java Timer Example

Java Timer Example:

Think of a scenario where I want my code to execute at a particular time in my application or at sometime later from the current time. In other words, I want to schedule my task at the definite time. How can this be possible using Java Programming language?

Tutorial:

Java Timer class (java.util.Timer) allows an application to schedule the task on a separate background thread. Please note that by default the associated thread is a non-daemon thread i.e. application does not terminate pending timer thread to complete execution.However, you can change the associated thread to Timer Class as Daemon Thread during creation of Timer Object. (Learn more about Daemon Thread in java)

Timer Task:

Timer class needs Timer Task (java.util.TimerTask) (Runnable Object) to execute the task. This is the class where the actual logic implementation resides inside run method. Timer when scheduled, picks up Timer Task and executes (once or repetitive as the case may be).

How to schedule Task:

Timer class provides various ways to schedule the task based on number of execution and rate of execution. Here are the list:

Method Signature

Purpose

schedule (TimerTask task, Date time)  Schedule task at specified Date time. It will be executed only once on the time specified
schedule (TimerTask task, Date firstTime, long period)  Schedule task at specified Date time. It will start executing from the specified date time and then repeat after the period specified henceforth
schedule (TimerTask task, long delay) Schedule task after delay time. It will be executed only once on the delay time specified from the current time
schedule (TimerTask task, long delay, long period) Schedule task after delay time with fixed delay period time unit execution thereafter. 
scheduleAtFixedRate (TimerTask task, Date firstTime, long period) Schedule task at specified Date time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 
scheduleAtFixedRate (TimerTask task, long delay, long period Schedule task after delay time with fixed rate execution. It will start executing from the specified date time and then repeat after the period specified henceforth. If the task couldn't start at the specified time, the next task will get triggered before the period time to adjust the fixed rate. 


How Java Timer works internally:

Internally Timer uses binary heap data structure to store Timer tasks. The constructor to create Timer object also creates Timer Thread with it and schedule method put the task on binary heap. It works on Object.wait() call to maintain Thread wait and notify.
Timer class is also thread-safe so multiple threads can simultaneously use it.

Java Timer Code Example :

import java.util.Timer;
import java.util.TimerTask;
public class JavaTimer {
  public static void main(String[] args){
  Timer timer = new Timer();
  TimerTask task = new TimerTask() {
      @Override
   public void run() {
    System.out.println("Inside Timer Task" + System.currentTimeMillis());
       }
  };
  System.out.println("Current time" + System.currentTimeMillis());
  timer.schedule(task, 10000,1000);
  System.out.println("Current time" + System.currentTimeMillis());
   }
}

Output :

Current time1455469505220
Current time1455469505221
Inside Timer Task1455469515222
Inside Timer Task1455469516222
Inside Timer Task1455469517222
Inside Timer Task1455469518222
Inside Timer Task1455469519222
Inside Timer Task1455469520222
Inside Timer Task1455469521222
Inside Timer Task1455469522222
Inside Timer Task1455469523222
Inside Timer Task1455469524222
Inside Timer Task1455469525222
Inside Timer Task1455469526222
Inside Timer Task1455469527222
Inside Timer Task1455469528223
Inside Timer Task1455469529223 and it goes on

Analysis :

The call to timer.schedule(task, 10000,1000) is going to schedule the task which is going to execute for first time (on another thread) after 10 second from this call. After that it will call again after delay of 10 seconds. It is important to mention here that if the task cannot be started after 10 seconds, next task call will not get pre-pond. So here the delay time between two consecutive task is fixed.

How to cancel Timer Thread:

To cancel and discard all scheduled task from the queue, cancel() method needs to be called. If there is any on-going execution, it will not interrupt in between. Rather it cancels all other scheduled task from the queue and after completion of on-going task(if any), Timer thread exits gracefully.

How to cancel already running Task:

To cancel already running task, you need to identify check points where you need to cancel the task. Take AtomicInteger as signal to cancel task and change its value inside cancel() method and when cancel signal comes then inside your task there are various check points which will check the value  and exit the task (Please remember to do cleanup/rollback as needed before existing the task thread).

Wednesday, February 10, 2016

Daemon Thread in java

Introduction:

In Java, Daemon Threads are one of the types of thread which does not prevent Java Virtual Machine (JVM) from exiting.
The main purpose of daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

How to create a Daemon Thread in Java:

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

Code Example:


public class DaemonThread {

public static void main(String[] args) {
System.out.println("Entering Main Thread");
Thread t = new Thread(new Runnable(){
@Override
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Executing Daemon Thread");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.setDaemon(true); // Thread becomes daemon thread here
t.start();
System.out.println("Exiting Main Thread");
}
}

Here is the sample output:

Output1:
Entering Main Thread
Exiting Main Thread

Output2:
Entering Main Thread
Exiting Main Thread
Executing Daemon Thread
Executing Daemon Thread

Explanation

In the above code example, main thread is spawning a daemon thread, Here main thread is the only non-deamon thread. As soon as the main thread execution completes, JVM exits and daemon thread dies alongwith.

The above code example and output illustrates the following:
  • JVM doesn't wait for the daemon thread to complete its task
  • Daemon thread dies as soon as JVM exits

Finding if the thread is daemon or not:

To know if a thread is daemon or not, you can check with Thread.isDeamon(). If returns true, the thread is daemon.