Sunday, October 23, 2016

Jenkins Interview Questions and Answers

Jenkins is one of the tools for continuous integration and these days more applications are using Jenkins for automated integration. Here are few important questions and answers on Jenkins.

1. What is Jenkins?

Jenkins is an open source application for continuous integration and continuous delivery of application software.


2. What is Continuous Integration?

Typically, there are multiple developers writing code for a single application, so we need to perform integration test by integrating each new piece of code via testing it through as many tests as possible. This practice is called continuous Integration. Jenkins besides Hudson, Bamboo etc provides tools for continuous integration.


3. Tell me few advantages of Jenkins?

Here are some advantages of using Jenkins (or by any matter any integration tools) :-

(a) It saves developer time: 

The foremost advantage of using Jenkins is that since most of the integration task is being handled by Jenkins (via automatic integration), the developer time is focused on development activities mostly.

(b) Improved software quality

Since the software is being tested immediately after any code check-in, it keeps the quality check frequently, thus improving overall software quality.

(c) Faster Delivery

Jenkins automatically does continuous integration, which leads to very early detection of bugs / defects and hence it leads to faster delivery of software.

(d) Decreased development time

Since most of the integration work is automated by Jenkins, it leads to the faster development of application.

(e) Easily portable: 

Since Jenkins is developed using Java, it can be easily portable to other platforms.

(f) Early tracking of defects: 

Jenkins helps tacking of defects at very early stage in development environment only rather than production environment.

(g) Email Notification to developers: 

Jenkins can be easily integrated with LDAP server, so developer are notified about build success / failure via mail.


4. What are the commands to start Jenkins manually?

Commands:
<jenkins_url>/restart :  Force restart (will not wait for ongoing build to complete)
<jenkins_url>/safeRestart : Wait for all builds to complete before restarting.


5. Mention few plugins of Jenkins?

Here are some plugins that can be used with Jenkins:

  • Delivery Pipeline
  • Join Plugin
  • Copy Artifact 
  • Git 
  • Android Emulator 
  • Cobertura 
  • Email-ext 
  • Docker 
  • Amazon EC2
  • Openstack Cloud
  • CloudBees Folders

6. What are the two most important components Jenkins is integrated with?

Jenkins is integrated with these two components mainly:
(a) Version Control System like SVN, GIT
(b) Build tools like Maven

That's all for some important questions and answers on Jenkins. I will add more questions and answers later.

Saturday, September 24, 2016

How to 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.

Sunday, September 4, 2016

Java Multi-threading Interview Questions and Answers - Series I

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.

Saturday, August 13, 2016

Ansible local action

Originally published by me in another blog as Ansible local_action and reproduced here for larger audience. This is also an important interview questions on Ansible.

In this article, we will learn some of the use-cases and advantages of Ansible local action.



Ansible local_action module:

Consider the problem / usecase scenario where we want to run tasks on the system which runs the Ansible-playbook command. In other words, how can we run for eg. shell command on the local machine parallely while playbook is already running. Also, how can we make sure that some tasks has been fulfilled in order to run the other part of playbook on some other remote machine.

The solution to the above usecase is the local_action option provided by Ansible. It takes the module name and module argument and will run that module locally.



Example:





cat local_action.yml

---

- hosts: dev

  tasks:

    - name: remote running process

      shell: ps

      register: remote_process



    - debug: msg="{{ remote_process.stdout }} "



    - name: Running Local Process

      local_action: shell ps

      register: local_process



    - debug: msg="{{ local_process.stdout }}"

 

Consider this example, which is the playbook I will be using for local_action. If we run the above playbook, we can see that we have two tasks.




- name: remote running process

   shell: ps

   register: remote_process



 - name: Running Local Process

   local_action: shell ps

   register: local_process

 


Ansible local_action shell

The first task will run ps command (shell command) on the remote machine and to check the output of the command a register remote_process has been set.

The second task as shown in above example will run command on local machine due to the local_action module being specified.



How to run local actions?

To run local actions, we just need to define the module name (i.e. local_action module name) for the command or task to run.

For example:





ansible-playbook local_action.yml



PLAY [dev] ********************************************************************



GATHERING FACTS ***************************************************************

ok: [172.16.202.96]



TASK: [remote running process] ************************************************

changed: [172.16.202.96]



TASK: [debug msg="{{ remote_process.stdout }} "] ******************************

ok: [172.16.202.96] => {

    "msg": "  PID TTY          TIME CMD\n12775 pts/1    00:00:00 sh\n12776 pts/1    00:00:00 python\n12777 pts/1    00:00:00 ps "

}



TASK: [Running Local Process] *************************************************

changed: [172.16.202.96 -> 127.0.0.1]



TASK: [debug msg="{{ local_process.stdout }}"] ********************************

ok: [172.16.202.96] => {

    "msg": "  PID TTY          TIME CMD\n24362 pts/0    00:00:02 bash\n30565 pts/0    00:00:00 ansible-playboo\n30587 pts/0    00:00:00 sh\n30588 pts/0    00:00:00 python\n30593 pts/0    00:00:00 ps"

}



PLAY RECAP ********************************************************************

172.16.202.96              : ok=5    changed=2    unreachable=0    failed=0 





Analysis:

If we see the above command result, we find that the both output differ from each other because one is being run on local machine and another being run on remote machine.


Ansible local_action sudo:

If we want to make anisible use the remote user for local_action, use the -u option while running playbook. When it uses the user to sudo, it will ask for sudo password




ansible-playbook -i <inventory> ansible/local_action.yml -u <local user that can sudo with password> --ask-sudo-pass



Conclusion:

Ansible local_action is the way to make double sure that the some things are available before we jump to run on remote machine. Its like running pretest locally before running command or task on remote machine.

That's all about Ansible local_action usage and its purpose.



Friday, August 12, 2016

Design Pattern Interview Questions

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.

Saturday, July 30, 2016

Docker Interview Questions and Answers - Part II

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>


This article was originally published by me at Docker Interview Questions and reproduced here for larger audience. 

That's all for Part II series of Docker Interview Questions. I will keep posting more question in next series with more depth analysis. 

<<<<<< Docker Interview Questions - Part -I

Sunday, July 3, 2016

JBOSS Interview Questions and Answers

JBOSS Application server has a new name WildFly and it implements JAVAEE specification. For interview purpose, here are some questions along with its answers.


What is JBOSS? 

JBoss is an open source application server based on JaVA EE technology. Being JAVAEE based, it can run on cross-platform. It was embedded with Apache Tomcat web server. It runs under any JRE version of 1.3 or later . JBoss supports JNDI, Servlet/JSP (Tomcat or Jetty), EJB, JTS/JTA, JCA, JMS, Clustering (JavaGroups), Web Services (Axis), and IIOP integration (JacORB).


Define JBoss cache? 

Caching usuall comes into picture when there are frequent access to some objects. Likewise, multiple and frequently accessed Java objects are cached by using JBoss cache to improve the performance of e-business applications. 


What is JBoss JBPM? 

JBoss JBPM is a workflow and Business Process Manager engine. As a BPM engine, it enables the creation of business processes that coordinates between people, applications and services. The combination of workflow applications development with process design is a feature of JBoss jBPM. The business process has GUI (Graphical User Interface) to facilitate a strong link between the business analyst and technical developer. This feature is provided by the JBoss jBPM process designer.


How do you monitor JBoss and detect the bottleneck of an application? 

At first, you need to measure different components of the application and then observe where the degradation is, and whether it is internal or external and which component is consuming maximum cpu. Using Joss JMX agents and monitoring the deployed components to the application server involves in the first step.

After observing which specific components or libraries spent most of time, one can then use Jprobe to examine that single object or the objects loaded in the memory.


What is JTA? 

Java Transaction API (JTA) specifies standard Java interfaces between a transaction manager and the parties involved in a distributed transaction system: the resource manager, the application server, and the transactional applications. It allows applications to perform distributed transactions, that is, transactions that access and update data on two or more resources.It consists of three elements: a high-level application transaction demarcation interface, a high-level transaction manager interface intended for an application server, and a standard Java mapping of the X/Open XA protocol intended for a transactional resource manager.


Which Hibernate object wraps the JDBC Connection? 

The Session interface wraps a JDBC Connection which is a single threaded object representing a single unit for application and persistent database. You can get the Session object from SessionFactory's openSession() method


Is the Session Factory Thread safe? 

Yes because many threads can simultaneously access it and request for sessions. It holds cached data that has been read in one unit of work and is likely to be reused in future unit of work. The best practice to create Session Factory object is when the application is initialized.


How can you start a JTA transaction from a Servlet deployed on JBoss? 

JBoss registers in the JNDI tree a JTA UserTransaction Object which can be user to manage a distributed transaction.


What if you need to span your transaction across multiple Servlet invocations?

You can't with a Servlet. A JTA transaction must start and finish within a single invocation (of the service() method). You should consider using a Stateful SB. In a SFSB with a JTA transaction, the association between the bean instance and the transaction is retained across multiple client calls.


What are the differences between EJB 3.0 and EJB 2.0? 

EJBs are now plain old Java objects (POJO) that expose regular business interfaces (POJO), and there is no requirement for home interfaces.
  • Use of metadata annotations, an extensible, metadata-driven, attribute-oriented framework that is used to generate Java code or XML deployment descriptors.
  • Removal of the requirement for specific interfaces and deployment descriptors (deployment descriptor information can be replaced by annotations).
  • Interceptor facility to invoke user methods at the invocation of business methods or at life cycle events.
  • Default values are used whenever possible (“configuration by exception” approach).
  • Reduction in the requirements for usage of checked exception.
  • A complete new persistence model (based on the JPA standard), that supersedes EJB 2.x entity beans

What is the difference between a local-tx-datasource and a xa-datasource? can you use transactions in both? 

A local-tx-datasource identifies a data source that uses transactions, even distributed trans actions within the local application server, but doesn’t use distributed transactions among multiple application servers. An xa-datasource on the other hand identifies a data source that uses distributed transaction among multiple application servers.


What do you need to set-up a cluster with JBoss? 


Basically starting JBoss with the “all” configuration contains everything needed for clustering:
It has all the libraries for clustering:
  • JGroups.jar, jboss-cache.jar
  • Clustered beans (cluster-service.xml)
  • HA-JNDI
  • HTTP session replications (tc5-cluster-service.xml)
  • Farming
  • HA-JMS

What optimization could I use if the EJB container is the only point of write access to the database? 

You could activate the "Commit Option A" that is the container caches entity bean state between transactions. This option assumesthat the container has exclusive access to the persistentstore and therefore it doesn’t need to synchronizethe in-memory bean state from the persistent store at the beginning of each transaction.


Which component handles cluster communication in JBoss?

The JGroups framework provides services to enable peer-to-peer communications between nodes in a cluster. It is built on top a stack of network communication protocols that provide transport, discovery, reliability and failure detection, and cluster membership management services.


Is it possible to put a JBOSS server instance into multiple cluster at the same time? 

It is technically possible to put a JBOSS server instance into multiple clusters at the same time, this practice is generally not recommended, as it increases the management complexity.


What do you know about Seam? 

Built on the standards JavaServer Faces and EJB 3.0, JBoss Seam unifies component and programming models and delivers a consistent and powerful framework for rapid creation of web applications with Java EE 5.0. Seam simplifies web application development and enables new functionality that was difficult to implement by hand before, such as stateful conversations, multi-window operation, and handling concurrent fine-grained AJAX requests. Seam also unifies and integrates popular open source technologies like Facelets, Hibernate, iText, and Lucene.


Does Seam run on other application servers besides JBOSS?

Seam runs beautifully on other application servers - just like everything else the Hibernate team does, this is not a JBoss-only thing.


Which JDK is needed to run Seam? 

Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0 features.


How would you convince my IT department to adopt SOA? 

In my opinion one of the biggest obstacle in the movement towards SOA adoption is the organization’s own IT department.Too many people in the IT organization conceive SOA as a technology concept only, and as such think of SOA as just a set of technologies and infrastructure for exposing, securing, running, and managing Services. Put it this way, SOA is nothing more than Web Services and standardized middleware. The critical flaw in thinking is confusing the technology that sits beneath the Services level of abstraction and the mechanism by which Services are accessed with the architectural approach that aims to decouple the implementation from the consumption and focus on sustainable architecture that allows for continuous change.

Successful SOA adoption requires a cultural shift in the way IT is done. The Service-oriented movement to agility and loose coupling demands a shift from traditional, waterfall styles of development (design-build-test-deploy-manage) to iterative approaches to continuous Service modeling


What do you think about BPEL and BPM ? How do they compare? 

In my opinion BPEL and BPM are quite different things so they cannot even be compared. The problems boils down to the fact that these years maybe BPEL has been marketed for something which isn't: that is a Business Process Management framework.
BPEL is made up for service orchestration, that is publishing new services as a function of other services.
while BPM si needed for handling human task management functionalities and subprocess management.


What is the difference between JAX--WS and JAX-RPC? 

Java API for XML-Based RPC (JAX-RPC) is a Legacy Web Services Java API, it uses SOAP and HTTP to do RPCs over the network and enables building of Web services and Web applications based on the SOAP 1.1 specification, Java SE 1.4 or lower.JAX-WS 2.0 is the successor to JAX-RPC 1.1. JAX-WS still supports SOAP 1.1 over HTTP 1.1, so interoperability will not be affected. However there are lots of differences:


  • JAX-WS maps to Java 5.0 and relies on many of the features new in Java 5.0 like Web Service annotations.
  • JAX-RPC has its own data mapping model, JAX-WS's data mapping model is JAXB. JAXB promises mappings for all XML schemas.
  • JAX-WS introduces message-oriented functionality, dynamic asynchronous functionality which are missing in JAX-RPC.
  • JAX-WS also add support, via JAXB, for MTOM, the new attachment specification.

Do you know how you could add support for Web Service transactions? 

JBossTS supports Web Services transactions, including extended transaction models designed specifically for loosely-coupled, long running business processes. J2EE transactions can integrate seamlessly with Web Services transactions using our integrated, bi-directional transaction bridge. Interoperability with many other vendors is provided out-of-the-box and JBoss is an active participant in these standards.


What version of JBoss AS do I need to run Seam? 

For Seam 1.3: Seam was developed against JBoss 4.2. Seam can still be run against JBoss 4.0. The seam documentation contains instructions for configuring JBoss 4.0.


For Seam 1.2: Since Seam requires the latest edition of EJB3, you need to install JBoss AS from the latest JEMS installer. Make sure that you select the "ejb3" or "ejb3+clustering" profile to include EJB3 support. Also, the jboss-seam.jar library file from the Seam distribution must be included in each Seam application you deploy. Refer to examples in Seam distribution (inside the examples directory) to see how to build and package Seam applications.


Can I run Seam outside of JBoss AS? 

Yes, you can run Seam applications in plain Tomcat 5.5+ or in the Sun GlassFish application server. To run Seam application in Tomcat, you need a number of additional library files and a few configuration files to bootstrap the JBoss EJB3 inside Tomcat. Please refer to the deploy.tomcat ANT build target for the Seam booking example (in the examples/booking directory of the Seam distribution) for more on how to build a Tomcat WAR for Seam applications. Refer to this blog post on how to run Seam in Sun's Glassfish application server.


Can I run Seam in a JAVAEE environment? 

Yes, as of Seam 1.1, you can use Seam in any JAVAEE application server, with one caveat: you will not be able to use EJB 3.0 session beans. However, you can use either Hibernate or JPA for persistence, and you can use Seam JavaBean components instead of session beans.


Can I run Seam with JDK 1.4 and earlier? 

No, Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0 features.


Where can I find Seam examples and documentation? 

The source code and build script of all Seam example applications are included in the examples directory of the Seam distribution.


Is it true that Seam only works with JSF? 


Seam only supports JSF as a view framework at this time. We plan to support other web frameworks in the future. We like JSF because it is a component-based UI framework, which fits really well with Seam's component-based approach to business objects and persistence objects. Seam made a major improvement to JSF by eliminating almost all XML configuration for backing beans i.e. you can now define back beans from POJOs or EJB3 components using simple annotations. We recommend you use Facelets, instead of JSP, with JSF. Facelets provide a powerful templating framework, better appplication performance, and allows us to write much simpler JSF pages. 


Can I use AJAX with Seam? 

A: Yes, Seam provides excellent support for AJAX. First, Seam supports the ICEfaces and Ajax4JSF Ajax component libraries for JSF. If you prefer a more "old fashioned" approach, Seam provides a complete JavaScript remoting framework which lets you call Seam components and subscribe to JMS topics directly from the client. 


Can I unit test Seam applications without starting the Application Server?

Yes, Seam provides its own integration test framework based on TestNG. You can easily mock all Seam services using those facilities without ever loading an application server or a database.

Tuesday, June 14, 2016

Ansible Interview Questions

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.



Friday, April 1, 2016

JMS Interview Questions and Answers

Java Message Service is an interface for point-to-point queuing and Topic (Publish/Subscribe). For interview purpose, here are some questions along with its answers.

What is JMS? 

Java Message Service is an interface implemented by most JAVAEE containers to provide point-to-point queuing and topic (publish/subscribe) behavior. JMS is frequently used by EJB's that need to start another process asynchronously.
For example, instead of sending an email directly from an Enterprise JavaBean, the bean may choose to put the message onto a JMS queue to be handled by a Message-Driven Bean (another type of EJB) or another system in the enterprise. This technique allows the EJB to return to handling requests immediately instead of waiting for a potentially lengthy process to complete.


What type messaging is provided by JMS? 

JMS provides both synchronous and asynchronous messaging.


How many messaging models does JMS provide? 

JMS provides two messaging models, publish-and-subscribe (Topic) and point-to-point queuing.


What is point-to-point model in JMS? 

A point-to-point model is based on the concept of a message queue i.e. Senders send messages into the queue, and the receiver reads messages from this queue. In the point-to-point model, several receivers can exist, attached to the same queue but the message will be delivered to one of them. Its a one-to-one communication.


What are the advantages of JMS? 

One of the main advantages of JMS is that it is asynchronous. Thus not all the components need to be up all the time for the application to function as a whole.


What is the publish-and-subscribe model in JMS? 

A publish-subscribe model is based on the message topic concept. In other words, publishers send messages to a topic, and all subscribers of the given topic receive these messages. Its a one-to-many communication


What is JMS administered object? 

A preconfigured JMS object (a resource manager connection factory or a destination) created by an administrator for the use of JMS clients and placed in a JNDI namespace


What is publish/subscribe messaging? 

With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.

Which models are supported by JMS? 
Publish/subscribe (pub/sub). This model allows a client (publisher) to send messages to a JMS topic. These messages are retrieved by other clients (subscribers) (it may happen so that a topic has no subscribers) asynchronously. Pub/sub model requires a broker distributing messages to different consumers.


What are the different parts of a JMS message? 

A JMS message contains three parts:

  • Header
  • Optional properties 
  • Optional body



What is the main parts of JMS applications? 

The main parts of JMS applications are:

  • ConnectionFactory and Destination
  • Connection
  • Session
  • MessageProducer
  • MessageConsumer
  • Message



What is the role of the JMS Provider? 

The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.


What is the difference between Java Mail and JMS Queue? 

JMS is the ideal high-performance messaging platform for intrabusiness messaging, with full programmatic control over quality of service and delivery options.
JavaMail provides lowest common denominator, slow, but human-readable messaging using infrastructure already available on virtually every computing platform.


Does JMS specification define transactions? 

JMS specification defines a transaction mechanisms allowing clients to send and receive groups of logically bounded messages as a single unit of information. A Session may be marked as transacted. It means that all messages sent in a session are considered as parts of a transaction. A set of messages can be committed (commit() method) or rolled back (rollback() method). If a provider supports distributed transactions, it's recommended to use XAResource API.


What is synchronous messaging? 

Synchronous messaging involves a client that waits for the server to respond to a message. So if one end is down the entire communication will fail.


What is asynchronous messaging? 

Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. So even if the client is down , the messaging will complete successfully.


How does a typical client perform the communication?  


  1. Use JNDI to locate administrative objects.
  2. Locate a single ConnectionFactory object.
  3. Locate one or more Destination objects.
  4. Use the ConnectionFactory to create a JMS Connection.
  5. Use the Connection to create one or more Session(s).
  6. Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
  7. Perform your communication.



What is JMS session? 

A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted, locally transacted, or participating in a distributed transaction.


Where should we use JMS?

JMS is the ideal high-performance messaging platform for intrabusiness messaging, with full programmatic control over quality of service and delivery options.


What is the difference between durable and non-durable subscriptions? 

A durable subscription gives a subscriber the freedom of receiving all messages from a topic, whereas a non-durable subscription doesn't make any guarantees about messages sent by others when a client was disconnected from a topic.


What is the difference between Message producer and Message consumer? 

Messaging systems provide a host of powerful advantages over other conventional distributed computing models. Primarily, they encourage "loose coupling" between message consumers and message producers. There is a high degree of anonymity between producer and consumer: to the message consumer, it doesn't matter who produced the message, where the producer lives on the network, or when the message was produced.