Google

Dec 19, 2011

Tricky Java interview questions and answers

Q. Can interfaces contain inner classes?
A. Yes, but not recommended as it can compromise on clarity of your code.

The interface with an inner class for demo purpose only

package innerstatic;

public interface InterfaceWithInnerClass {
    
    
    public static final Util UTIL = new Util( );
    

    public String getName(); // next node in this list

    public final static InterfaceWithInnerClass FIELD =
      //anonymous inner class as the interface field declaration  
      new InterfaceWithInnerClass() {
          public String getName() {
            return "Peter";
        }
    };

    
 //static inner class
    public static class Util {
        public String getDetail(){
            return FIELD.getName() + " age 25";
        }
    }
}


The class that implemnts the above interface.


package innerstatic;

public class Test implements InterfaceWithInnerClass {

    @Override
    public String getName() {
        return FIELD.getName() + " : " + UTIL.getDetail();
    }
    
    public static void main(String[] args) {
        System.out.println(new Test().getName());
    }
}


The output is:

Peter : Peter age 25


Q. What happens if you pass a primitive int value to a method that accepts

a) long primitive
b) float primitive
c) Float object
d) Number object

A.

a) A widening conversion takes place from int to long. So, no compile or run time error.
b) A widening conversion takes place from int to float. So, no compile or run time error.
c) compile-time error. primitive type int can be auto-boxed to type Integer, but type Integer and Float are derived from type Number, and don't have the parent child relationship. So, they cannot be implicityly or exlplicitly cast to each other.
d) primitive type int can be auto-boxed to type Integer, and then implicitly cast to type Number as Number and Integer have the parent child relationship. So, no compile or run time error.



Q. What is the purpose of the intern( ) method in the String class?
A. It is used for moving the String objects created with the "new" operator to the internal string pool.



Q. Why is the String class in Java is final immutable object?
A.

Security: the system can pass on sensitive info like password, credit card number, etc as read-only information without worrying that it will be altered.

Immutable objects are thread-safe. Two or more threads can  work on an immutable object at the same time without any possibility of conflict. Immutable String objects are great to be used as keys in a map without worrying about the key getting modified.

To keep things simple. Since final, you can't subclass it to have two different String objects that have the same value. It is also easier to implement some of the string methods like substring because of its immutability.


Q. Is the finally block is always guaranteed to be execute?
A. No. The finally block is not executed under circumstances like

  • System.exit( ) in try or catch block.
  • If the thread executing the try or catch block is killed or interrupted. 
  • If an exception is thrown from the finally block and not handled, then remaining code in the finally block is ignored.

Q. What is the purpose of 'const' reserved keyword in Java?
A. It is reserved, but not currently used in Java. 

Labels:

Java multi-threading interview questions and answers - coding

The Java multi-threading questions are very popular with the job interviewers as it can be not only hard to grasp, but also concurrency issues are very hard to debug and fix. So, it really pays to have people with the good understanding in this key area. We looked at some basic questions and answers at Java multi-threading questions and answers. Let's look at more coding based questions and answers to build up on what we had learned before.


Q. Explain how you would get a Thread Deadlock with a code example?
A. The example below causes a deadlock situation by thread-1 waiting for lock2 and thread-0 waiting for lock1.



package deadlock;

public class DeadlockTest extends Thread {

    public static Object lock1 = new Object();
    public static Object lock2 = new Object();

    public void method1() {
        synchronized (lock1) {
            delay(500);  //some operation
            System.out.println("method1: " + Thread.currentThread().getName());
            synchronized (lock2) {
                System.out.println("method1 is executing .... ");
            }
        }
    }

    public void method2() {
        synchronized (lock2) {
            delay(500);   //some operation
            System.out.println("method1: " + Thread.currentThread().getName());
            synchronized (lock1) {
                System.out.println("method2 is executing .... ");
            }
        }
    }

    @Override
    public void run() {
        method1();
        method2();
    }

    public static void main(String[] args) {
        DeadlockTest thread1 = new DeadlockTest();
        DeadlockTest thread2 = new DeadlockTest();

        thread1.start();
        thread2.start();
    }

    /**
     * The delay is to simulate some real operation happening.
     * @param timeInMillis
     */
    private void delay(long timeInMillis) {
        try {
            Thread.sleep(timeInMillis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

The output will be something like:

method1: Thread-0
method1 is executing .... 
method2: Thread-0
method1: Thread-1
---deadlock ----- can't proceed further



Q. What happens if you restart a thread that has already started?
A. You will get the following exception


Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.start(Thread.java:595)
 at deadlock.DeadlockTest.main(DeadlockTest.java:38)



Q. Can you write a program with 2  threads, in which one prints odd numbers and the other prints even numbers up to 10?
A. In Java, you can use wait(  ) and notifyAll(  ) to communicate between threads. The code below demonstrates that.




Firstly, create the thread classes and the main method that creates the thread and run it.

package multithreading;

public class NumberGenerator extends Thread {

    private NumberUtility numberUtility;
    private int maxNumber;
    private boolean isEvenNumber;
    

    public NumberGenerator(NumberUtility numberUtility, int maxNumber, boolean isEvenNumber) {
        this.numberUtility = numberUtility;
        this.maxNumber = maxNumber;
        this.isEvenNumber = isEvenNumber;
    }

    public void run() {
        int i = isEvenNumber == true ? 2 : 1;
        while (i <= maxNumber) {
            if(isEvenNumber == true) {
                numberUtility.printEven(i);
            }
            else {
                numberUtility.printOdd(i);    
            }
            
            i = i + 2;
        }
    }
    
    
    public static void main(String[] args) {
        NumberUtility numUtility = new NumberUtility(); //single instance shared by oddGen and evenGen threads
        final int MAX_NUM = 10; 

        //create 2 threads, one to generate odd numbers and the other to generate even numbers
        NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false);
        NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true);
        
        oddGen.start();  //start the thread - invokes the run() method on NumberGenerator
        evenGen.start(); //start the thread - invokes the run() method on NumberGenerator
        
    }

}

Next, create the utility class that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods.


package multithreading;

import static java.lang.System.out;

public class NumberUtility {

    boolean oddPrinted = false;

    public synchronized void printOdd(int number) {

        while (oddPrinted == true) {
            try {
                wait();   // waits until notified by even thread

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

        out.println("printOdd() " + number);
        oddPrinted = true;
        notifyAll();  //notify all waiting threads

    }

    public synchronized void printEven(int number) {
        while (oddPrinted == false) {
            try {
                wait();  //waits until notified by the odd thread

            } catch (InterruptedException e) {

            }
        }

        oddPrinted = false;
        out.println("printEven() " + number);
        notifyAll();  //notify all waiting threads
    }
}


The output will be something like

printOdd() 1
printEven() 2
printOdd() 3
printEven() 4
printOdd() 5
printEven() 6
printOdd() 7
printEven() 8
printOdd() 9
printEven() 10 


Note: This a typical example of splitting tasks among threads. A method calls notify/notifyAll( ) as the last thing it does (besides return). Since the printOdd( ) and printEven( ) methods were void, the notifyAll( ) was the last statement. If it were to return some value, the notifyAll( ) would have been placed just before the return statement.

Q. Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5?

A. In Unix, a pipe (“|”) operator helps you to redirect output from one command to another. PipedReader and PipedWriter classes in java.io package helps you to do the same. It helps you to redirect the read input into writer seamlessly. In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process (i.e same address space)



Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

package multithreading;

import java.io.IOException;
import java.io.PipedWriter;

public class NumberWriter extends Thread {

    private PipedWriter writer;
    private int maxNumber;
    private boolean isEvenNumber;

    public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {
        this.writer = writer;
        this.maxNumber = maxNumber;
        this.isEvenNumber = isEvenNumber;
    }

    public void run() {
        int i = 1;
        while (i <= maxNumber) {
            try {
                if (isEvenNumber && (i % 2) == 0) {
                    writer.write(i);
                } else if (!isEvenNumber && i%2 != 0) {
                    writer.write(i);
                }
                ++i;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final int MAX_NUM = 10;

        PipedWriter oddNumberWriter = new PipedWriter();
        PipedWriter evenNumberWriter = new PipedWriter();

        NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);
        NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);
        NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);

        oddGen.start();
        evenGen.start();
        receiver.start();

    }

}


The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of 5, it prints the numbers and the sum.

package multithreading;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class NumberReceiver extends Thread {

    private PipedReader oddReader;
    private PipedReader evenReader;

    public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {
        try {
            this.oddReader = new PipedReader(oddWriter);
            this.evenReader = new PipedReader(evenWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        int odd =0, even=0;
        
        try {
            while (odd != -1) {
                odd = oddReader.read();
                even = evenReader.read();
                
                if ((odd + even) % 5 == 0) {
                    System.out.println("match found " + odd + " + " + even + " = " + (odd + even));
                }
            }
               
        } catch (IOException e) {
            System.exit(1);
        }
       
        
    }
}


The output will be something like

match found 7 + 8 = 15


Note: The above problem can also be solved with a blocking queue as described in multi-threading with blocking queues questions and answers.



Java multi-threading interview questions and answers: overview 
Java multi-threading questions and answers with blocking queue 

Labels:

Dec 14, 2011

JSF Interview Questions and Answers: event handling

Q. What are the different types of JSF events?
A. JSF is an event driven framework.

  • Action Events: bound to UI Command objects like a Command Button or a Hyper-link. Whenever a user presses a Command Button or clicks a hyperlink these Events get generated.
  • Value Change Events: bound to UI Components like Text Field, Check-Box, List and Radio Buttons. The Value Change Event is fired as soon as the value that is displayed in the view is modified.
  • Phase Events: As you saw earlier in the JSF overview blog, the request processing life-cycle in JSF includes six phases and any JSF implementation will fire Phase events during the start and end of each phase. If we want to capture the Phase Events, then can define a Phase Listener. These are handy for debugging as well.



Q. How are events handled in JSF? What is the difference between these event handling mechanisms?
A. Action handlers and event listeners provide an event driven mechanism. Every time a user does something like clicking a button, selecting an item from a drop down, or submitting a form, an event occurs. Event notification is then sent via HTTP to the server and handled by the FacesServlet. Events can invoke custom business logic or initiate page navigation.


JSF provides two types of methods for handling events; listeners and action handlers, both of these may be defined within a managed bean. A listener takes an FacesEvent as a parameter and a void return type, while an action handler takes no parameters and returns a String.


Example 1: An event handler


<!-- login.xhtml-->
<h:inputText id="useName" />
<h:inputSecret id="password" />
<h:commandButton action="#{login.submit}">


<!-- faces-config.xml-->
<navigation-rule>
     <from-view-id>/login.xhtml</from-view-id>
  <navigation-case>
     <from-action>#{login.submit}</from-action>
  <from-outcome>success</from-outcome>
  <to-view-id></to-view-id>
  </navigation-case>    
</navigation-rule


//Login managed bean
public String submit(  ) {
      //do some action
       ....

       return "success"  //navigate to /home.jsf     
}




Example 2: An event handler with an event listener

Action listeners are provided by JSF to make it easier to handle action events. An advantage of using a listener is that the FacesEvent object provides additional information, such as the form element that initiated the event. An action handler in contrast has no knowledge of the source of the event, but based upon its return value, can initiate page navigation. The example below shows using both event handlers and event listeners.

<h:commandButton value="Search" actionListener="#{orders.confirm}" action="#{orders.search}" />

In the above example, when the button is clicked the JSF implementation calls the action listener during the Invoke Application phase. The action listener method then has a chance to perform any processing related to the command element selected by the user. You can perform any processing you need to inside the method. The method can have any name, must be public, return void, and accept an ActionEvent as its only parameter.

public void confirm(ActionEvent event) {
       int calculatedAge = calculateAgeFromDOB();
       if (event.getComponent().getId().equals("confirm")) {
            //perform some action
   ....
       }
    
    else if(event.getComponent().getId().equals("validate")){
         //perform some other action
   ....
    }
}


After the action listener method is called, the method bound by the action attribute will be called, and the JSF implementation will determine where to navigate next.

public String search( ) {
    //some action logic
 ...
 //navigation logic
 return "success";
}

Since the action listener method is called before the action handler method, the action listener method can modify the response that the action method returns.

An action listener can also be implemented as shown below.

<h:commandButton id="submitOrderSearch" value="Search" action="#{orders.search}" >
     <f:actionListener type="com.MyAppActionListenerImpl" />
</h:commandButton>

The listener class can be implemented as shown below:

package com;

...

public class MyAppActionListenerImpl implements ActionListener {

    public void processAction(ActionEvent aev) {
      System.out.println(aev.getId());
   ...
   }

}


A ValueChangeEvent is useful whenever you want to be notified when there is a change in the value of a component, such as text modification in a text field or a check box selection. Most JSF components support the valueChangeListener attribute.

<h:inputText  id="orderStatus"  valueChangeListener="#{orders.onStatusChange}" />

The managed bean method:

public void onStatusChange(ValueChangeEvent vce) {
     System.out.println(vce.getId());
  System.out.println(vce.getOldValue());
  System.out.println(vce.getNewValue());
  ....
}

This can also be implemented as shown below.

<h:inputText  id="orderStatus" >
    <f:valueChangeListener type="com.MyAppValueChangeActionListenerImpl" />
</h:imputText>

The managed bean method:

package com;

...

public class MyAppValueChangeActionListenerImpl implements ValueChangeListener {

    public void processValueChange(ValueChangeEvent vce) {
      System.out.println(vce.getId());
   System.out.println(vce.getOldValue());
      System.out.println(vce.getNewValue());
      ....
   }

} 


More JSF Interview Questions and Answers

Labels:

Dec 10, 2011

JSF Interview Questions and Answers: postback and viewstate

Q. What is the difference between initial request and postback?
A. Initial request (e.g. HTTP GET) is the request that is made from a browser in order to display a page. Postback happens when the browser posts the page back to the server with form values, etc. Initial request is created by clicking a link, pasting an URL in address bar, while a postback request is create by posting a form by clicking a submit button or any post request. Initial request passes only restore View & Render Response phases, while postback request process under all phases described in the JSF life cycle diagram.


During the restore view phase of the life cycle, ViewHandler retrieves the ResponseStateManager object in order to test if the request is a postback or an initial request. If a request is a postback, the restoreView method of ViewHandler is called. This method uses the ResponseStateManager object to re-build the component tree and restore state.
The ResponseStateManager object is the only one that knows what rendering technology is being used and is therefore the only one that can look at a request, which is rendering-technology specifiec. Here are the basic steps.

  • An isPostBack method on ResponseStateManager returns true if the current request is a postback.
  • A getState method is called by the restoreView method of ViewHandler to retrieve the component tree state from the current request.
  • A writeState method that writes out the state to the client. This method is called by the renderView method of ViewHandler during the render response phase.

Q. What is a viewstate in JSF?
A. In JSF, there is a viewstate associated with each page, which is passed back and forth with each submits. The reason for the viewtate is that the HTTP is a stateless protocol. The state of the components across requests need to be maintained. The viewstate can change in between requests as new controls like UIInput can be added or modified. The view state is divided into two parts.

Part 1: Structure of the components
Part 2: Defines the state of the components. For example. enabled/disabled, input values, checked/unchecked, selected item, etc.

Understanding the JSF lifecycle helps understand the viewstate.



It can be achieved by either storing the viewstate on the server side in a session and then passing the viewstate id to the client via a hidden field as shown below:




Server side: In web.xml file, set the state saving strategy

<context-param>
     <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
     <param-value>server</param-value>
</context-param>

The hidden field passed to the client

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="cdx43wedsfdg654ed" />

Client side: serializing the view state on the client. Do the following in web.xml

<context-param>
     <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
     <param-value>client</param-value>
</context-param>


More JSF Interview Questions and Answers

Labels:

Dec 9, 2011

JSF Interview Questions and Answers: Seam

Q. How does Seam framework fit in with the JSF framework?
A. JSF's major shortcoming is its heavy reliance on the HTTP session, especially when propagating data across a sequence of pages. Seam rectifies this with a conversational scope. Seam provides some hooks into the JSF life cycle to achieve this along with other benefits.




More JSF Interview Questions and Answers

Labels:

Dec 8, 2011

Observer design pattern for publish/Subscribe model

The design patterns are very popular with the interviewers and Java/J2EE Job Interview Companion covers GoF design patterns, JEE design patterns, and EJB design patterns. This blog entry covers the observer design pattern.

Q. What is an observer design pattern?
A. The Observer pattern is a behavioral design pattern that  allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

  • When a change to one object requires changing of others, and you don't know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.
  • When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.

Examples:

  • Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.
  • Programming a stock market application to know when the price of a stock changes.
  • Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject. 






Here is some pseudo code of this third scenario

STEP 1: Define the Subject and Observer interfaces

This is the subject interface


package com;

public interface ReportExecutor {
    public void addHandler(ReportHandler rh);
    public void removeHandler(ReportHandler rh);
    public void processReport(String message);
}


This is the observer interface

package com;

public interface ReportHandler {
    //handles report
    public void handleMessage(String message);
}


STEP 2: Define the concrete subject and observers.


The concrete subject

package com;

import java.util.ArrayList;
import java.util.List;

public class SalesReportExecutor implements ReportExecutor {
    
    //list of observers that register their interest in SalesReport
    private List<reporthandler> reportHandlers = new ArrayList<reporthandler>();

    @Override
    public void addHandler(ReportHandler rh) {
        reportHandlers.add(rh);
    }

    @Override
    public void processReport(String message) {
        for (ReportHandler reportHandler : reportHandlers) {
            reportHandler.handleMessage(message);
        }
    }

    @Override
    public void removeHandler(ReportHandler rh) {
        reportHandlers.remove(rh);

    }

}

The concrete observers

package com;

public class LoggingReportHandler implements ReportHandler {

    @Override
    public void handleMessage(String message) {
        //handles report by formatting and printing
        System.out.println("Logging report  " + message);
    }
}


package com;

public class EmailReportHandler implements ReportHandler {

    @Override
    public void handleMessage(String message) {
        //handles the report by formatting it differently and emailing.
        System.out.println("Emailing report " + message);
        //logic to email report.
    }
}


STEP 3: Finally, the JMS listener class that uses the subject. The JMS Listener class listens on a queue for presence of a report.

package com.mgl.mts.fix;

import javax.jms.Message;
import javax.jms.TextMessage;

public class MyAppListener {

    public void onMessage(Message message) {
        if (message instanceof TextMessage) {

            ReportExecutor executor = new SalesReportExecutor();
            executor.addHandler(new LoggingReportHandler());
            executor.addHandler(new EmailReportHandler());
            executor.processReport(message.toString());

        } else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}

Q. Can you list some Java interfaces that use the observer design pattern?
A.

  • The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.
  • The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.
  • In the java.util package, we have the Observer interface and the Observable class.
  • In an MVC (Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer  and is automatically notified by the model of changes in state that require a screen update.


Q. What are the pros and cons of an Observer design pattern?
A.

PROS:

  • Loose coupling between Subject and Observer: The subject knows only a list of observers, that implement the Observer interface, it does no know the concrete implementation of the Observer.
  • Broadcast communication: An event notification is broadcast to observers irrespective of the number of Observers

CONS:

  • If not used carefully the observer pattern can add unnecessary complexity.
  • The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order of notification. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering. 
  • The possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.



Other design patterns - real life examples

Labels:

Dec 6, 2011

Spring Interview Questions and Answers: JNDI, JMS, and bean scopes

Spring Interview Questions and Answers Q1 - Q14 are FAQs

Q1 - Q4 Overview & DIP Q5 - Q8 DI & IoC Q9 - Q10 Bean Scopes Q11 Packages Q12 Principle OCP Q14 AOP and interceptors
Q15 - Q16 Hibernate & Transaction Manager Q17 - Q20 Hibernate & JNDI Q21 - Q22 read properties Q23 - Q24 JMS & JNDI Q25 JDBC Q26 Spring MVC Q27 - Spring MVC Resolvers

Q23. How can you configure JNDI in spring application context?
A23. Using "org.springframework.jndi.JndiObjectFactoryBean". For example,

Example 1:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"   scope="singleton">
  <property name="jndiName">
   <value>java:comp/env/jdbc/dataSource/myapp_ds</value>
  </property>
 </bean>



Example 2:

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:myapp.properties" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

The myapp.properties

jndi.naming.myapp=java:comp/env/jdbc/dataSource/myapp_ds
...

Use the property "jndi.naming.myapp"

<bean id="mfsShyDS" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>${jndi.naming.myapp}</value>
</property>
</bean>


Q. What is difference between singleton and prototype bean?
A. If you had noticed the above examples, the scope was set to "singleton". This means single bean instance per IOC container. In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.



Scopes:
  • singleton – Return a single bean instance per Spring IoC container. you would use singletons for stateless services where you will only have one instance of each service, and since they are stateless they are  threadsafe.
  • prototype – Return a new bean instance each time when requested. you would use prototypes for stateful scenarios like request actions (e.g. in struts), so a new object gets created to handle each request.

the default scope is singleton. The web-aware scopes are
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session.



Q24. How would you use Spring to send JMS based messages
A24. Here is some pseudocode that uses Spring with JNDI and JMS to send messages. It assumes that the ConnectionFactory and Destination values are configured via JNDI.

To send messages

  • Locate a ConnectionFactory, typically using JNDI.
  • Locate a Destination, typically using JNDI.
  • Create a Spring JmsTemplate with the ConnectionFactory.
  • Create a JmsTemplate using the ConnectionFactory.
  • Inject the JmsTemplate and the destination to your "MyAppMessageSender" to send messages using the jmsTemplate and the destination you just injected.
  • A sessiion needs to be created via the Spring class MessageCreator, and subsequently a message is created on the session created.

To receive messages

  • Locate a ConnectionFactory, typically using JNDI.
  • Locate a Destination, typically using JNDI.
  • Create a message listener class (e.g. com.MyAppListener)
  • Create a JMS message container by injecting ConnectionFactory, Destination, and the listener. The container is responsible for binding the listener to the queue.


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"> 

 <!-- JNDI configuration -->
    <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate"> 
        <property name="environment"> 
            <props> 
                <prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop> 
                <prop key="java.naming.provider.url">jnp://localhost:1099</prop> 
                <prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop> 
                <prop key="java.naming.security.principal">admin</prop> 
                <prop key="java.naming.security.credentials">admin</prop> 
            </props> 
        </property> 
    </bean>  
  
  
    <bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> 
        <property name="jndiTemplate" ref="jndiTemplate" /> 
        <property name="jndiName" value="MyAppConnectionFactory" /> 
    </bean> 
 
  <bean id="jmsQueueDestination" class="org.springframework.jndi.JndiObjectFactoryBean"> 
        <property name="jndiTemplate" ref="jndiTemplate" /> 
        <property name="jndiName"> 
            <value>queue/MyAppQueue</value> 
        </property> 
    </bean> 
 
 <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
           <property name="connectionFactory" ref="jmsConnectionFactory"/>
 </bean>
 
 
 <bean id="sender" class="com.MyAppMessageSender"> 
         <property name="connectionFactory" ref="connectionFactory"/>
   <property name="queue" ref="jmsQueueDestination"> 
     
    </bean>


 <!-- POJO Messgae Listener -->
 <bean id="jmsMessageListener" class="com.MyAppListener" />
  
   
   <!-- Connects the queue to the POJO message listener -->
    <bean id="jmsContainer"  class="org.springframework.jms.listener.DefaultMessageListenerContainer"> 
        <property name="connectionFactory" ref="jmsConnectionFactory" /> 
        <property name="destination" ref="jmsQueueDestination" /> 
        <property name="messageListener" ref="jmsMessageListener" /> 
    </bean> 

  
</beans> 


Here is the message sender -- com.MyAppMessageSender

package com;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;


public class MyAppMessageSender {
    
    private JmsTemplate jmsTemplate; 
    private Destination destination; 

   
    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setDestination(Destination destination) {
        this.destination = destination;
    } 
    
    
    public void sendMessage() { 
        this.jmsTemplate.send(this.destination, new MessageCreator() { 
            public Message createMessage(Session session) throws JMSException { 
              return session.createTextMessage("message from myapp"); 
            } 
        }); 
    } 
}


Here is the message receiver -- com.MyAppListener. The onMessage(...) method in invoked asynchronously when a message apper in the destination (e.g. Queue/Topic)

package com;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class MyAppListener implements MessageListener {
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                System.out.println(((TextMessage) message).getText());
            }
            catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
        else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
}

Labels:

Dec 5, 2011

Hibernate Interview questions and answers: cacheing

Q. What is a second-level cache in Hibernate?
A. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the SessionFactory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. The second-level cache needs to be explicitly configured. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.

The Hibernate configuration looks like:

<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

The ehcache.xml can be configured to cache objects of type com.myapp.Order as shown below

<cache name="com.myapp.Order"
   maxElementsInMemory="300"
   eternal="true"
   overflowToDisk="false"
   timeToIdleSeconds="300"
   timeToLiveSeconds="300"
   diskPersistent="false"
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU"       
/>

second-level cache reduces the database traffic by caching loaded objects at the SessionFactory level between transactions. These objects are available to the whole application, not just to the user running the query. The 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached. It is imperative to implement proper cache expiring strategies as caches are never aware of changes made to the persistent store by another application. he following are the list of possible cache strategies.

  • Read-only: This is useful for data that is read frequently, but never updated. This is the most simplest and best-performing cache strategy.
  • Read/write: Read/write caches may be appropriate if your data needs to be updated. This carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when session.close() or session.disconnect() is called.
     
  • Nonstrict read/write: This is most appropriate for data that is read often but only occasionally modified.This strategy does not guarantee that two transactions won't simultaneously modify the same data.
     
  • Transactional: This is a fully transactional cache that may be used only in a JTA environment.


It can be enabled via the Hibernate mapping files as shown below:

<class name="com.myapp.Order">

    <cache usage="read-write"/>
    ....
</class>

Note: The usage options are: transactional|read-write|nonstrict-read-write|read-only. The cache can also be enabled at different granular level (e.g. parent, children, etc). The active orders will be cached for 300 seconds.



Q. How does the hibernate second-level cache work?
A. Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database. Hibernate's static initialize() method, which populates a proxy object, will attempt to hit the second-level cache before going to the database. The Hibernate class provides static methods for manipulation of proxies.


public final class Hibernate extends Object {
    ....
 public static void initialize(Object proxy)  throws HibernateException 
    .... 
}


As a consequence of using the Hibernate second-level cache, you have to be aware of the fact that each call of a data access method can either result in a cache hit or miss. So, configure your log4j.xml to log your hits and misses.

<logger name="org.hibernate.cache">
   <level value="DEBUG" />
</logger>

Alternatively, you can use Spring AOP to log the cache access on your DAO methods.


The second level cache is a powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtle in their behavior. Especially, the interaction with the Hibernate session can lead to unwanted behavior.



Q. What is a query cache in Hibernate?
A. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries. Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.

Query query = session.createQuery("from Order as o where o.status=?");
query.setInt(0, "Active");
query.setCacheable(true); // the query is cacheable
List l = query.list();

You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.

<property name="hibernate.cache.use_query_cache">true</property>


Q. What are the pitfalls of second level and query caches?
A. Memeory is a finite resource, and over use or incorrect useage like cacheing the Order object and all its referenced objects can cause OutOfMemoryError. Here are some tips to overcome the pitfalls relating to cacheing.

1. Set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters. Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.

In the example below, the entire customer and everything he/she references would be held in cache until either the query cache exceeds its configured limits and it is evicted, or the table is modified and the results become dirty.

final Customer customer = ... ;
final String hql = "FROM Order as order WHERE order.custOrder = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer);
q.setCacheable(true);

Instead of setting the whole customer object as shown above, just set the id.

final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);

2. Hibernate's query cache implementation is pluggable by decorating Hibernate's query cache implementation. This involves overriding the put( ) method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists.


3. If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.


Here are some general performance tips:

1. Session.load will always try to use the cache. Session.find does not use the cache for the primary object, but cause the cache to be populated. Session.iterate always uses the cache for the primary object and any associated objects.

2. While developing, enable the show SQL and monitor the generated SQL.

<property name="show_sql">true</property>

Also enable the "org.hibernate.cache" logger in your log4j.xml to monitor cache hits and misses.




More Hibernate Related Interview Questions and Answers

Labels:

Dec 1, 2011

Spring Interview Questions and Answers: Hibernate integration

Spring Interview Questions and Answers Q1 - Q14 are FAQs

Q1 - Q4 Overview & DIP Q5 - Q8 DI & IoC Q9 - Q10 Bean Scopes Q11 Packages Q12 Principle OCP Q14 AOP and interceptors
Q15 - Q16 Hibernate & Transaction Manager Q17 - Q20 Hibernate & JNDI Q21 - Q22 read properties Q23 - Q24 JMS & JNDI Q25 JDBC Q26 Spring MVC Q27 - Spring MVC Resolvers

Q15. How would you integrate Hibernate with Spring?
A15. The hibernate can be wired up via Spring as shown below.

STEP 1: The Hibernate properties.

   
   <!--  hibernate properties-->
   <bean id="myappHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
            </props>
        </property>
    </bean>


STEP 2: The DataSource.

    
    
 <!-- datasource configured via JNDI-->    
  <bean id="myappDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/jdbc/dataSource/myapp-ds</value>
        </property>
  </bean>    

 
 STEP 3: The hibernate mapping files. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.


    
 
   <bean name="myappHibernateMappingFiles" class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="sourceList">
            <list>
                <value>hbm/Order.hbm.xml</value>
                <value>hbm/Trade.hbm.xml</value>
                <value>hbm/Customer.hbm.xml</value>
            </list>
        </property>
    </bean>
   
   
STEP 4: An empty interceptor

    
    
    <!-- An interceptor that does nothing. May be used as a base class for application-defined custom interceptors. -->
    <bean id="myappEntityInterceptor" class="org.hibernate.EmptyInterceptor" />
   

   
STEP 5: Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

    
    
    <!-- Define the session factory -->
    <bean name="myappSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" autowire="byName">
        <property name="hibernateProperties">
            <ref bean="myappHibernateProperties"/>
        </property>
        <property name="dataSource">
            <ref bean="myappDataSource"/>
        </property>
        <property name="mappingResources">
            <ref bean="myappHibernateMappingFiles"/>
        </property>
        <property name="entityInterceptor">
            <ref bean="myappEntityInterceptor"/>
        </property>
    </bean>
   

STEP 6: The hibernate template. Helper class that simplifies Hibernate data access code.    

    
    
    <!-- Hibernate Template -->
    <bean name="myappHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" autowire="no" scope="prototype">
        <property name="sessionFactory">
            <ref bean="myappSessionFactory"/>
        </property>
        <property name="allowCreate">
            <value>false</value>
        </property>
        <property name="maxResults">
            <value>50000</value>
        </property>
        <property name="flushMode">
            <value>3</value>
        </property>
    </bean>

   
STEP 7: The repository class for data access logic.

    
    
    <!-- Constructor Inject the Template into your Repository classes  (Data acess layer)  -->
     <bean id="myappOrderRepository" class="com.HibernateOrderRepository">
        <constructor-arg><ref bean="myappHibernateTemplate" /></constructor-arg>
    </bean>

   
STEP 8: The service class that uses one or more repositories.    

    
     
     <!-- Service Layer: myappOrderRepository is injected via setter injection  -->
     <bean id="myappOrderService" class="com.OrderServiceImpl">
           <property><ref bean="myappOrderRepository" /></property>
    </bean>
    

 STEP 9: The repository interface and class that makes use if the hibernate template.

    
package com;

import com.ObjectNotFoundException;

public interface OrderRepository {
    public Order load(Long identity) throws ObjectNotFoundException;
    public void save(Order order);
}



The template.load, template.save, etc are database operations via the HibernateTemplate.

    
package com;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.ObjectNotFoundException;
import com.Order;
import com.OrderRepository;


public class HibernateOrderRepository implements OrderRepository {
    
    private static final Logger LOG = Logger.getLogger(HibernateOrderRepository.class);

    private final HibernateTemplate template;
  

    public HibernateOrderRepository(HibernateTemplate template) {
        this.template = template;
    }

    @Override
    /**
     * Read Order from database
     */
    public Order load(Long identity) throws ObjectNotFoundException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading " + identity);
        }
        try {
            return template.load(Order.class,identity);
        } catch (HibernateObjectRetrievalFailureException e) {
            throw new ObjectNotFoundException(identity + " not found", e);
        } 
    }

    /**
     * Save the record to database
     * @param order     */
    public void save(Order order) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Saving " + order);
        }
        template.save(order);
    }
}



Q16: How do you wire up a transaction manager?
A16:

STEP 1: Define a transaction manager.

<!-- Transaction Manger -->
 <bean name="myappTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="myappSessionFactory" />
    </bean>


STEP 2: Create a transaction interceptor that uses the above transaction manager.

<bean id="myappHibernateInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager" ref="myappTransactionManager" />
        <property name="transactionAttributes">
            <props>
                <prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
            </props>
        </property>
    </bean>


STEP 3: Create other optional interceptors for logging, deadlock retry, etc.

<!-- SERVICE INTERCEPTORS -->
    
    <bean id="myappLoggingInterceptor" class="com.MyAppLoggingInterceptor" />
    <bean id="myappDeadlockRetryInterceptor" class="com.OracleDeadlockRetryInterceptor" />

STEP 4: Wire up the interceptors to an abstract service

<!-- SERVICES -->
    
    <bean id="myappAbstractService" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="interceptorNames">
            <list>
                <value>myappLoggingInterceptor</value>
                <value>myappDeadlockRetryInterceptor</value>
                <value>myappHibernateInterceptor</value>
            </list>
        </property>
    </bean>
 


STEP 5: The concrete service that uses the myappOrderRepository along with the interceptors. Especially the "myappHibernateInterceptor" that performs transaction demarcation.

<bean id="myappOrderService" parent="myappAbstractService">
     <property name="proxyInterfaces">
            <value>com.mgl.mts.oms.model.service.OrderService</value>
        </property>
        <property name="target">
            <bean class="com.OrderServiceImpl">
             <constructor-arg><ref bean="myappOrderRepository" /></constructor-arg>
            </bean>
        </property>
    </bean>



STEP 6 The OrderServiceImpl class looks like

package com;

import ....

public class OrderServiceImpl implements OrderService {

    private final Logger LOG = Logger.getLogger(OrderServiceImpl.class);

    private final OrderRepository orderRepository;

    public OrderServiceImpl(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }
    
    //......  
}

Note: The OrderServiceImpl will have the interceptors turned using AOP to manage transaction, logging, and deadlock retry. The diagram below gives a big picture of interceptors, service, and repository.


Note: The deadlock retry filter is an interesting one. When an exception is thrown, it is inspected using a pattern matching (i.e. regular expression)  to see if it is due to deadlock. If it is due to deadlock the invocation is repeated. This makes the call again to the target, which is the OrderServiceimpl via the TransactionInterceptor, which starts a new transaction.


Here is an example of the custom interceptor -- myappLoggingInterceptor. Aspect-Oriented Programming (AOP) offers a better solution to many problems. he AOP Alliance project (aopalliance-x.x.jar) is a joint open-source project between several software engineering people who are interested in AOP and Java.


package com.test;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class MyAppLoggingInterceptor implements MethodInterceptor {
    
    private static final Logger LOG = Logger.getLogger(MyAppLoggingInterceptor.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        long begin = System.currentTimeMillis();
        
        //proceed to the next interceptor on the chain 
        Object result = invocation.proceed();
        
        long end = System.currentTimeMillis();;
        
        LOG.info("Time elapsed " + (end - begin) + " ms");
        
        return result;
    }

}


The deadlock retry interceptor


package com.test;

import java.sql.SQLException;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class OracleDeadlockRetryInterceptor implements MethodInterceptor {
    
    private static final Logger LOG = Logger.getLogger(OracleDeadlockRetryInterceptor.class);
    
    private int attempts = 3;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        return doInvoke(invocation, 1);
    }

    private Object doInvoke(MethodInvocation invocation, int count) throws Throwable {
        try {
            //proceed to next interceptor
            return invocation.proceed();
        } catch (Exception exception) {
            if (!isDeadlockException(exception)) {
                throw exception;
            }
            LOG.warn("A Database deadlock occured. Will try again.", exception);
            if (count < attempts) {
                count++;
                return doInvoke(invocation, count);
            }
            throw new SQLException("Service Invocation failed " + attempts
                        + " times with a SQLException.", exception);
        }
    }

} 

More Spring Interview Questions and Answers

Labels: ,