Sunday, 25 December 2016

Ansible Interview Questions and Answers

What is Ansible?


Ansible is a software tool to deploy application using ssh without any downtime. It is also used to manage and configure software applications. You don't need any agent on server to deploy application using Anisible. It is developed in Python language.


Brief me some advantages of Ansible?

(a) Agent-less
(b) Very low overhead
(c) Good performance.


Design Pattern Interview Questions and Answers

Design Pattern Interview Questions:

Define Creational design patterns?

Creational patterns are used to define and describe how objects are created at class instantiation time. Usually an abstract super class contains the details of the classes that are instantiated and the client class is unaware of such details. 
Singleton pattern, Factory pattern, Abstract Factory pattern are examples of creational design pattern.

A class instance can be created using new operator. Why should we use creational design patterns to create objects?

Using new operator to create objects is a valid approach but its like hard coding the object type. If we are 100% sure that our object will be of the same class all the time, then we use new operator to create an object. In scenarios where the nature of the object can change according to the nature of the program, we use creational design patterns which offer flexible approach for creating class instances.

Which object oriented method is used by the creational patterns to instantiate object?

Creational patterns use inheritance to decide the object to be instantiated.

Define a factory with respect to software development.

Object construction is referred as a factory. It is used to isolate the creation of objects from their usage. If you are using factory methods for objects creation, then the new derived types will cause no code change in your classes that are using factories.

When will you use a Factory Pattern?

The factory pattern is preferred in the following cases: - a class does not know which class of objects it must create - 
Factory pattern can be used where we need to create an object of any one of sub-classes depending on the data provided.
Give an example of factory method that creates and return an object based on a String parameter. You have following interface. Create 2 implementations for it and write a factory method for it.

Example:



package factory.pattern;



public interface IMessage {



void sendMessage(String phNr, String messageContent);



}




SMSMessage and MMSMessage are implementing IMessage and MessageFactory class provides a factory method getMessageSender (String arg) method.





package factory.pattern;



public class SMSMessage implements IMessage{
@Override
public void sendMessage(String phNr, String messageContent) { System.out.println(String.format("Sending SMS contnet: %s to %s", messageContent, phNr));
}
}
package factory.pattern;
public class MMSMessage implements IMessage{
@Override
public void sendMessage(String phNr, String messageContent) {
System.out.println(String.format("Sending MMS contnet: %s to %s", messageContent, phNr)); }
}
package factory.pattern;
public class MessageFactory {
public static IMessage getMessageSender (String arg){
IMessage message = null;
if(arg != null){
if(arg.equals("SMS")){
message = new SMSMessage();
} else if (arg.equals("MMS")){
message = new MMSMessage();
}
}
return message;
}
}


Given below is a class that provides a static factory method. Write a class to use this factory method.

Example

package factory.pattern;



public class MessageFactory {



public static IMessage getMessageSender (String arg){



IMessage message = null;



if(arg != null){



if(arg.equals("SMS")){



message = new SMSMessage();



} else if (arg.equals("MMS")){



message = new MMSMessage();



}



}



return message;



}



}



// IMessage interface - it can have many implementations



package factory.pattern;



public interface IMessage {



void sendMessage(String phNr, String messageContent);



}


 

Based on the command line argument, factory method will return an implementation of IMessage.



package factory.pattern;



public class MainTestClass {



public static void main(String[] args) {



IMessage messageSender = MessageFactory.getMessageSender(args[0]);



if(messageSender !=null){



messageSender.sendMessage("1234", "Hello World");



}



}



}


 


Name the creational design pattern that provides abstraction one level higher than the factory pattern.

Abstract factory pattern provides abstraction one level higher than factory pattern. It encapsulates a group of individual factories.


Write example of abstract factory pattern using following interfaces.




public interface GUIFactory {



public Button createButton();



}



interface Button {



public void paint();



}


 

WInFactory and OSXFactory are the implementations of GUIFactory. TestApplicationRunner provides createOsSpecificFactory method that returns GUIFactory.



class WinFactory implements GUIFactory {



public WinButton createButton() {



return new WinButton();



}



}



class OSXFactory implements GUIFactory {



public OSXButton createButton() {



return new OSXButton();



}



}



class WinButton implements Button {



public void paint() {



System.out.println("I'm a WinButton");



}



}



class OSXButton implements Button {



public void paint() {



System.out.println("I'm an OSXButton");



}



}



class Application {



public Application(GUIFactory factory) {



Button button = factory.createButton();



button.paint();



}



}



public class TestApplicationRunner {



public static void main(String[] args) {



new Application(createOsSpecificFactory(args[0]));



}



public static GUIFactory createOsSpecificFactory(String arg) {



if (arg.equals("0)) {



return new WinFactory();



} else {



return new OSXFactory();



}



}



}


 


What is the difference between factory design pattern and abstract factory design pattern?

Both are creational design patterns. Factory pattern is said to be there if there is method in a class that is used to create class instances. Any class can have factory methods. Using abstract factory pattern, an instance of a class is created that has only factory methods.


When will you use Abstract factory pattern?

Abstract factory pattern is preferred in situations where the names of actual implementing classes are not needed to be known at the client side. This would mean that we can change the implementation from one factory to another.


Which of the following relation can hold between abstract factory and factory method?IS-AHAS_A

Abstract factory HAS_A (not always) factory method.


What benefits you achieve with factory method?

Factory method makes the code more flexible and reusable by eliminating the instantiation of application-specific classes. This way the code deals only with the interface and can work with any concrete class that supports this interface.


What is the liability of using factory method for object creation?

We need to do subclassing just to instantiate a particular class.


Name the design pattern in which a class delegates the responsibility of object instantiation to another object via composition.

Abstract factory pattern


Name the design pattern that uses inheritance and relies on a subclass to handle the desired object instantiation.

Factory method pattern 


Example




public class MazeFactory {


public Maze makeMaze() {return new Maze();}


public Room makeRoom(int n) {return new Room(n);}


public Wall makeWall() {return new Wall();}


public Door makeDoor(Room r1, Room r2) {


return new Door(r1, r2);}


}


public class EnchantedMazeFactory extends MazeFactory {


public Room makeRoom(int n) {return new EnchantedRoom(n);}


public Wall makeWall() {return new EnchantedWall();}


public Door makeDoor(Room r1, Room r2)


{

return new EnchantedDoor(r1, r2);}

}


 


What type of methods are defined in MazeFactory class?

MazeFactory class contains a collection of factory methods.


Name the AbstractFactory in the given code.

MazeFactory is acting as both an AbstractFactory and a ConcreteFactory.


Which design pattern you will use if your system being developed must use just one of a set of families of products?

Abstract factory pattern can be used if system being developed must use just one of a set of families of products.


What is singleton design pattern?

Singleton design pattern allows us to use just one instance of a particular class. It insures that one and only once instance of a particular class is used when requested.


Give an example scenario where you will use singleton pattern.

Assume what we are writing an application that needs to log events in a log file. Logging is done with timestamp. We do not want to have more than one instances of Logger otherwise the log file will be created with every instance. In this case, we use Singleton pattern and instantiate the logger when the first request comes or when the server is started.


Write singleton example?

The following class shows how to write a singleton class:






public class SingletonObjectTest {





private static SingletonObject singletonObject;





private SingletonObjectTest() {





}





public static SingletonObjectTest getSingletonObject() {





if (singletonObject == null) {





singletonObject = new SingletonObjectTest();





}





return singletonObject;





}





}


 


Can you name some design patterns that make use of singleton pattern?

The Abstract Factory, Builder, and Prototype patterns may use singleton pattern. Also facade objects are often singletons.


How to you prevent instantiation of a singleton class from other classes?

Singleton class can have a private constructor with zero argument to prevent instantiation from other classes. For example:






public class SingletonTest {





private SingletonTest() { }





}

 

What are the drawbacks of using singleton design pattern?

The following drawbacks of Singleton pattern must be considered before applying it to any solution: - it introduces global state into an application and thus it makes unit testing far more difficult -access to the singleton in a multi-threaded context must be serialized.

Name the creational design pattern that is used to build complex objects step by step.

Builder pattern builds complex objects from simple ones. It separates the construction of complex objects from their representation. The purpose of builder pattern is to abstract steps of object construction so that different implementations of these steps can construct different representations of objects.


What is the role of director in builder pattern implementation?

The sequence of object creation is managed by director class. It receives a Concrete Builder (implementation of abstract interface for creating objects) as a parameter and executes the necessary operations on it.


Write an example to show how builder pattern can be applied.

The following example uses builder pattern to construct a Pizza object using PizzaBuilder.






public class Pizza {



private String dough;



private String sauce;



private String topping;



public String getDough() {



return dough;



}



public void setDough(String dough) {



this.dough = dough;



}



public String getSauce() {



return sauce;



}



public void setSauce(String sauce) {



this.sauce = sauce;



}



public String getTopping() {



return topping;



}



public void setTopping(String topping) {



this.topping = topping;



}



Pizza(PizzaBuilder builder) {



dough = builder.getDough();



sauce = builder.getSauce();



topping = builder.getTopping();



}



@Override



public String toString() {



return "Dough:"+dough +" Topping:"+topping+" Sauce:"+sauce;



}



}



public class PizzaBuilder {



String dough;



String sauce;



String topping;



public String getDough() {



return dough;



}



public String getSauce() {



return sauce;



}



public String getTopping() {



return topping;



}



public PizzaBuilder setDough(String dough) {



this.dough = dough;



return this;



}



public PizzaBuilder setSauce(String sauce) {



this.sauce = sauce;



return this;



}



public PizzaBuilder setTopping(String topping) {



this.topping = topping;



return this;



}



public Pizza build() {



return new Pizza(this);



}



}



public class PizzaBuilderExample {



public static void main(String[] args) {



PizzaBuilder hawaiianPizzaBuilder = new PizzaBuilder()



.setDough("cross").setTopping("ham+pineapple").setSauce("mild");



Pizza hawaiianPizza = hawaiianPizzaBuilder.build();



System.out.println("Hawaiian Pizza: "+hawaiianPizza);



}



}


 


When cloning an object is preferred over creating a new one?

If cost of creating a new object is larger than the cost of cloning the object, then it is better to clone the object.

What is Prototype pattern?

Prototype simply means making a clone and it is used to cloning an object to avoid its creation. Java provides an interface called Cloneable whose method clone() is used to clone an object.

Java Multi-threading Interview Questions and Answers

Java Multi-threading is quite tricky to understand. But if you understand its basics clearly, all other aspects to understand become so easy. Here are the first series of Java Multi-threading Interview Questions and Answers.

What are the different ways to create Threads in Java?

There are three ways to create threads in Java:
(a) By implementing runnable interface
(b) By extending Thread Class
(c) Using ThreadPoolExecutor to create one or more threads

Why the wait and notify methods are part of Object class and not Thread class?

For thread to go on wait state, its requires that it should wait on a particular Java Object so that the same object can be notified to make the thread back to runnable state. 

What is difference between wait and notify

wait method of Object class put the calling thread into wait state from running state whereas notify method put the waiting thread back to runnable state.

Tell me the difference between notify and notifyAll method

Suppose there are more than one threads waiting on an object, if we call notify method, only one thread will be back to runnable state out of n waiting threads. So the number of waiting threads will be  n - 1. 
notifyAll method will wake up all the threads waiting on an Object to the runnable state.

What is the benefit of concurrent classes

Java 5 provides a series of concurrent classes like ConcurrentHashMap and others, the benefit of which is that we can access those data-strucure classes simultaneously by multiple threads parallely without worrying about thread synchronization and we don't have to wait for one task to complete to start another.

How is HashMap different from ConcurrentHashMap

HashMap is not threadsafe i.e. the developer needs to take care of synchronization if multiple threads are accessing the HashMap whereas in Concurrent HashMap we dont have to worry about synchronization if multiple threads are accessing it.
Moreover, with no sychrnoziation overhead to be created by developer, ConcurrentHashMap is much faster than HashMap (considering we need to implement synchornization mechanism to work with HashMap)

Hashtable and ConcurrentHashMap both are threadsafe, which one  you will prefer

I will prefer ConcurrentHashMap because its performance is much faster as compared to Hashtable as all the methods of Hashtable are synchronized, there is overhead for acquiring and releasing object locks in Hashtable.
With multiple processor in place, apart from synchronization overhead, if multiple threads are calling the same method (for eg. put method), ConcurrentHashMap calls can go parallely and Hashtable calls needs to be executed synchronously.

How does String class is threadsafe if its internal implementation is not synchronized

String is a immutable class, so its value once set via constructor, it will not change and so all threads will see the same value and can be used across threads. This is true for every immutable class and we dont require synchronization to make it threadsafe. In other words, immutable class like String is a constant, so it can be safely used by multiple threads without fearing the change of value by one and dirty read by another (which is not possible here).

Do you need to hold lock of the object before you call Object.wait() or Object.notify()

Yes, for any call to wait and notify method, the calling thread must have the monitor lock with it. If we call it without having the monitor lock, it will throw exception.

If yes, then will Object.wait() will keep the lock forever

No, calling to Object.wait() will put the current thread in wait state waiting for notify on that object and release the lock by current thread immediately.

What is Deadlock

Deadlock is the situation where one thread is holding a resource and waiting for another resource and the other thread is holding that another resource and waiting for a resource. This situation is called deadlock.

What is Atomic in java

Java 5 introduce Atomic Variable such as AtomicInteger, AtomicLong and others. The benefit of using Atomic classes is that its operation cannot be interrupted in between. For example, i++ is a three step operation, fetching value of i from memory, increasing its value and putting back new value of i in memory. Any other thread can interrupt in between three calls whereas with Atomic classes it is just a one cpu call (all three combined), so a similar operation like i++ in AtomicInteger cannot be interrupted.

Will declaring a variable as volatile makes it a threadsafe

No, declaring a variable as volatile will only make sure that the it will always reads the memory value of variable and not the local thread cache. This means that if some other thread has updated the value, the current thread will only read the updated one (local cache copy may be dirty in this case). This in no case will make it threadsafe because changes by two threads can be overwritten by each other even though both threads are reading the in-memory data.
The benefit of using volatile in multi-threaded environment is that if one thread is making changes to a variable and other threads are only reading it, the changes made by that thread will be immediately visible to other threads.

That's all for Series -I of Core Java Multi-threading Interview Questions with Answers. If you are looking for all Java Interview questions, here is the link.

Solve Producer Consumer problem in Java using wait and notify method

Producer Consumer problem can be easily solved by using just wait and notify method using inter-thread communication where one thread is used to produce and another thread is used to consume. Here the wait and notify method will be used for inter-thread communication to notify other party (Producer by Consumer thread and vice-versa).

To solve this problem, I have used the ArrayList as shared object, where producer thread puts the object (Just Integer in this case) and consumer thread consumes the object (integer). Interestingly, I have used the same list object as monitor lock, thus removing the additional overhead to create shared monitor lock.

Here is the code example:


import java.util.ArrayList;

public class ProducerConsumer {

 public static void main (String[] args) {
  ArrayList<Integer> list = new ArrayList<Integer>();
  Thread t1 = new Thread(new Producer(list));
  Thread t2 = new Thread(new Consumer(list));
  t1.start();
  t2.start();
  
 }
}

class Producer implements Runnable {
 
 private ArrayList<Integer> list;
 Producer(ArrayList<Integer> list) {
  this.list = list;
 }

 @Override
 public void run() {
  int count = 1;
  while(count <= 3) {
   synchronized(list) {
    list.add(count);
    System.out.println("Produced ::"+ count);
    count++;
    try {
     list.notify();
     list.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
  
 }
}


class Consumer implements Runnable {
 
 private ArrayList<Integer> list;
 Consumer(ArrayList<Integer> list) {
  this.list = list;
 }
 
 @Override
 public void run() {
  int count = 1;
  while(count <= 3) {
   synchronized(list) {
    while(list.size() == 0){
     try {
      list.notify();
      list.wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    Integer value = list.remove(0);
    System.out.println("Consumed ::"+ value);
    count++;
    try {
     list.notify();
     list.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
}

Output:

Produced ::1
Consumed ::1
Produced ::2
Consumed ::2
Produced ::3
Consumed ::3

Explanations:

In the above code example, we are starting two threads (one Producer and one Consumer). To avoid the consumer start executing and consuming first, I have put code to check if producer has already produced or not (i.e. if there is anything on list or not). This is to address race-condition between producer and consumer threads.
Here, the producer thread is putting 3 objects (Integer in the example) in the list. Please note that the call by Producer thread and Consumer thread to put objects and retrieve objects is synchronized on the same lock (array list object in this example). This way, we guarantee that either the code of producer or code of consumer is executing inside cpu and not both at the same time. We have produced three objects and consumed three synchronously i.e producer put one, consumer consumed then again producer produced another  and ...
So, when producer produced an object, it calls notify to make sure that if the consumer threads is in waiting state, it goes back to runnable state and ready to consume and the producer thread goes to wait state (and releasing the lock) and then consumer thread which has been in runnable states gets the lock (after producer releases it), consumes the object, notify the producer to produce another and same cycle repeats for the 3 times.



That's all for the solution of producer consumer problem using wait and notify method with the help of above code example. If you have any question. please feel free to ask in comment section.

Wednesday, 16 November 2016

[UPDATED] Top 20 Anisible Interview Questions and Answers

What is Ansible?


Ansible is a software tool to deploy application using ssh without any downtime. It is also used to manage and configure software applications. You don't need any agent on server to deploy application using Anisible. It is developed in Python language.


Brief me some advantages of Ansible?

(a) Agent-less
(b) Very low overhead
(c) Good performance.

Monday, 14 November 2016

Docker Interview Questions and Answers

In this article we will see important questions and answers on Docker for the purpose of interview preparation


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 doesn't have a state and its state never changes as it is just set of files whereas docker container has its execution state.


How do you create docker image?

Docker image are created using Docker file. Docker build is command to create docker image out of docker file

So you have the docker image, what is the next step?

With docker image, we can spawn as many containers as needed. All containers can be same instance or it can also be different instance, what I mean that if we are using the same command for creating multiple containers, all container will behave as same. However, if you choose different command to create container out of same image, it will provide different functionality altogether.

How to create docker container?

We can create docker container by running this command

docker run -t -i <image name> <command name>

This will create and start the container


How to know the container status?

Just fire docker ps -a to list out all running container with stauts (running or stopped) on a host


How to stop and restart the container?

  • To stop container, we can use docker stop <container id>
  • To start a stopped container, docker start <container id> is the command
  • To restart a running container, docker restart <container id>


That's all for Docker Interview Questions. I will keep posting more questions with more depth analysis.

Thursday, 10 November 2016

Control M Interview Questions and Answers

What is Control-M?

Control-M is a workload automation software. In other words, it is a batch scheduling software and originally developed for Mainframe but later expanded for distributed computing platform like Windows, Wnix, Linux and OpenVMS environments.


Can we adjust the display in Control-M?


Yes.


What are the different intervals to schedule workloads in Control-M?


You can schedule workloads on daily, weekly or monthly intervals depends on the requirement.


What all types of functions that Control-M can automate?


It can automate the following type of functions:

  • JCL (Job Control Language)
  • Batch Files
  • Shell Scripts
  • Database stored procedures
  • File Transfer
  • Web Services

How can we return panes to their original positions in Control-M?

From View Menus -> Dockable Windows -> Reset to Default Layout, we can return panes to their original positions.

What are the different data display format?

  • Flow Diagram
  • List
  • Gantt Chart

How to change password in Control-M?

You can change the password from Tools menu (Tools->Change Password) if change password option is not visible on Control-M/EM or Control-M/Desktop.