Popular Posts

Monday, June 13, 2011

Hibernate Interview Questions

What is “N+1 Select problem”

In my last two posts, I mentioned that immediate fetching or lazy fetching can cause ‘N+1 select problem’. If you are wondering what exactly is this, read on.

Consider the example of Department and Employees. When you call EntityLoad(”Department”), following sqls will be executed.

SELECT * FROM department;

SELECT * FROM employees WHERE deptId = ?

The first query will be executed once (1) and the second query will be executed as many times as the department (N). Thus the above entityLoad call results into ‘N+1 sql execution and thus can be a cause of performance bottleneck. Because of N+1 sqls, this is known as ‘N+1 select problem’. This will almost always happen when the fetching is “Immediate” (using fetch=”select”) or can happen with lazy loading.

With immediate fetching it is obvious why this would happen. When lazy=’true”, this can happen when the association is accessed immediately on each of the owning object (department in this case).

If you think this could be happening in your application, use either of these two options.

set lazy=”false” and use fetch=”join” so that the departments and its employees get loaded together. (Eager fetch)

Keep lazy=”true” but load the department using hql with join. So instead of using EntityLoad(”Department”), use

ORMExecuteQuery("from Department dept left join fetch dept.employees")

· The classic N+1 problem in encountered in a simple lazy load scenario in any general application.

1query to get all department objects with PK

SELECT deptID FROM department;

And then query to get all other details of a particular dept

SELECT * FROM department where deptID=?;

The second query is executed as many times (N) as the number of full records you want to fetch. Its when N is high, eager can be a good strategy.

What is Hibernate Proxy

1) Class can be mapped to a proxy instead to a table. When you actually call load on session it returns you proxy. This proxy may contain actual method to load the data.

2) By default Hibernate creates a proxy for each of the class you map in mapping file. This class contain the code to invoke JDBC. This class is created by hibernate using CGLIB

What is the difference between and merge and update

Update():- if you are sure that the session does not contains an already persistent instance with the same identifier,then use update to save the data in hibernate

Merge():-if you want to save your modificatiions at any time with out knowing abot the state of an session, then use merge() in hibernate.

Second Level Cache

Hibernate Session is a transaction-level cache of persistent data. It is possible to configure a cluster or JVM-level (SessionFactory-level) cache on a class-by-class and collection-by-collection basis.

usage="transactional|read-write|nonstrict-read-write|read-only" (1)

region="RegionName" (2)

include="all|non-lazy" (3)

/>

you can specify and elements in hibernate.cfg.xml.

Whenever you pass an object to save(), update() or saveOrUpdate(),

and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.

evict () method can be used to remove the object and its collections from the first-level cache

ScrollableResult cats = sess.createQuery("from Cat as cat").scroll(); //a huge result set

while ( cats.next() ) {

Cat cat = (Cat) cats.get(0);

doSomethingWithACat(cat);

sess.evict(cat);

}


What are the id generator classes in hibernate?
A: increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int


hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.


seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.


uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.


guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.


assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association

Java - Garbage Collection

How is the generational collector implemented in HotSpot(tm)?

The default collector in HotSpot has two generations:

1) young generation and the

2) tenured generation.

è Most allocations are done in the young generation. The young generation is optimized for objects that have a short lifetime relative to the interval between collections.

è Objects that survive several collections in the young generation are moved to the tenured generation.

è young generation is typically smaller and is collected more often. The tenured generation is typically larger and collected less often.

young generation collector is a copying collector.

young generation is divided into 3 spaces:

ü eden-space,

ü to-space, and

ü from-space

Allocations are done from eden-space and from-space. When those are full a young generation is collection is done. The expectation is that most of the objects are garbage and any surviving objects can be copied to to-space. If there are more surviving objects than can fit into to-space, the remaining objects are copied into the tenured generation. There is an option to collect the young generation in parallel.

What is the relevance of -XX:MaxNewSize? Where will the differences between -XX:NewSize and -XX:MaxNewSize grow, Eden or Survivor Spaces?

The young generation is set by a policy that bounds the size from below by NewSize and bounds it from above by MaxNewSize. As the young generation grows from NewSize to MaxNewSize, both eden and the survivor spaces grow.

How should the permanent generation be sized?

The permanent generation is used to hold reflective of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations. Generally, sizing of this generation can be ignored because the default size is adequate. However, programs that load many classes may need a larger permanent generation.

How can I increase the permanent generation size?

command line option -XX:MaxPermSize=

How do I know what classes are being loaded or unloaded?

command line options -XX:+TraceClassloading and -XX:+TraceClassUnloading

What is the best size for the young generation?

The young generation should be sized large enough so that short-lived objects have a chance to die before the next young generation collection. This is a tradeoff since a larger young generation will allow more time for objects to die but may also take longer to collect. Experiment with the size of the young generation to optimize the young generation collection time or the applicationthroughput.

What should I do if my application has mid- or long-lived objects?

Objects that survive a young generation collection have a copying cost (part of the algorithm for a young generation collection is to copy any objects that survive). Mid- or long-lived objects may be copied multiple times.

Use the -XX option MaxTenuringThreshold to determine the copying costs.

Use -XX:MaxTenuringThreshold=0 to move an object that survives a young generation collection immediately to the tenured generation. If that improves the performance of the application, the copying of long-lived objects is significant. Note that the throughput collector does not use the MaxTenuringThreshold parameter.

What type of collection does a System.gc() do?

An explicit request to do a garbage collection does a full collection (both young generation and tenured generation).

A full collection is always done with the application paused for the duration of the collection.

What is the Concurrent Mark Sweep (CMS) collector?

The Concurrent Mark Sweep (CMS) collector (or concurrent low pause collector) collects the tenured generation. It attempts to minimize the pauses due to garbage collection by doing most of the garbage collection work concurrently with the application threads.

What are the phases of the concurrent low pause collector?

There are six phases involved in the collection:

Phase 1 (Initial Checkpoint) involves stopping all the Java threads, marking all the objects directly reachable from the roots, and restarting the Java threads.

Phase 2 (Concurrent Marking) starts scanning from marked objects and transitively marks all objects reachable from the roots. The mutators are executing during the concurrent phases 2, 3, and 5 below and any objects allocated in the CMS generation during these phases (including promoted objects) are immediately marked as live.

Phase 3: During the concurrent marking phase mutators may be modifying objects. Any object that has been modified since the start of the concurrent marking phase (and which was not subsequently scanned during that phase) must be rescanned. Phase 3 (Concurrent Precleaning) scans objects that have been modified concurrently. Due to continuing mutator activity the scanning for modified cards may be done multiple times.

Phase 4 (Final Checkpoint) is a stop-the-world phase. With mutators stopped the final marking is done by scanning objects reachable from the roots and by scanning any modified objects. Note that after this phase there may be objects that have been marked but are no longer live. Such objects will survive the current collection but will be collected on the next collection.

Phase 5 (Concurrent Sweep) collects dead objects. The collection of a dead object adds the space for the object to a free list for later allocation. Coalescing of dead objects may occur at this point. Note that live objects are not moved.

Phase 6 (Resetting) clears data structures in preparation for the next collection.

What is the Parallel Garbage collector (-XX:+UseParallelGC)?

ü The new parallel garbage collector is similar to the young generation collector in the default garbage collector but uses multiple threads to do the collection.

ü By default on a host with N CPUs, the parallel garbage collector uses N garbage collector threads in the collection.

ü The number of garbage collector threads can be controlled with a command line option (see below).

ü On a host with a single CPU the default garbage collector is used even if the parallel garbage collector has been requested.

ü On a host with 2 cpus the Parallel garbage collector generally performs as well as the default garbage collector and a reduction in the young generation garbage collector pause times can be expected on hosts with more than 2 cpus.

What is the Parallel Young Generation collector (-XX:+UseParNewGC)?

The parallel young generation collector is similar to the parallel garbage collector (-XX:+UseParallelGC) in intent and differs in implementation.

Most of the above description for the parallel garbage collector (-XX:+UseParallelGC) therefore applies equally for the parallel young generation collector.

Unlike the parallel garbage collector (-XX:+UseParallelGC) this parallel young generation collector can be used with the concurrent low pause collector that collects the tenured generation.

Java Performance Tuning

What to monitor in OS Level

1) CPU Utilization

2) Network Traffic

3) Disk I/O

4) Virtual Usage Memory usage

5) Process and Kernal Locks

CPU Monitoring

1) High SYS /Kernal CPU time

2) Idle Cpu

- In Multi threaded applications and muticore system idle cpu can be an indicator of an application’s inability to scale.

3) High VCX ( voluntary Context Switching)

Tools for monitoring

1) Vmstat – (solaris & Linux) - Used to obtain Summaries of CPU’s Usage.

2) Task Manager (windows)

light-weight process (LWP)

is a means of achieving multitasking.

LWP runs in user space on top of a single kernel thread and shares its address space and system resources with other LWPs within the same process.

Network I/O

1) Network Utilization in terms of TCP statistics and established connections

Tools for monitoring

Netstat (solaris and linux)

Monitoring Disk I/o

1) Number of Disk accesses and average Latencies

2) Tools for monitoring

iostat (solaris and linux)

Virtual Memory :Fixing the swapping problem

1) Smaller Java Heap Size

2) Add Physical Memory

3) Reduce number of applications Running on the machine

Java - Class loaders



ClassLoaders

Ø Class loaders are hierarchical.

Ø Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM.

Ø Class loader creates a namespace.

All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader.

Ø API

===

A class loader is an object that is responsible for loading classes.

class ClassLoader is an abstract class.

Given the binary name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.



how is the very first class loaded?

The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again

Classes loaded by a child class loader have visibility into classes loaded by its parents

Explain static vs. dynamic class loading?



Java InterView Questions - Singleton

singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object.

the constructor is made protected (not private, because reuse and unit test could need to access the constructor).

A class designed to hold a singleton object must prevent multiple instantiations of itself from being created. This includes

  • making its constructor private
  • employing lock mechanisms to prevent an initialization routine from running simultaneously by multiple threads
  • ensuring the class is not serializable
  • ensuring the class cannot be cloned
  • preventing the class from being garbage collected if it was loaded by a custom class loader

What is Singleton? Have you used Singleton before?

Singleton is a class which has only one instance thought out the application and provides a getInstance() method to access the singleton instance.

Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?

Situations often will demand for the existence of only one object for a particular class in an Application. For example, the existence of only one Database Connection for a particular session, one object referencing the set of Global properties being shared across the various modules, etc. Such classes are candidates to be designated as Singletonclasses. The sole purpose of such a class is to ensure that only one instance of the class is created for the entire Application and that instance is shared across multiple clients.

how to make a class to behave as a Singleton class?

MyConnection.java

package tips.pattern.singleton;

public class MyConnection {

private static MyConnection connection = null;

private MyConnection(){

}

public static MyConnection getConnection(){

initObject();

return connection;

}

private static void initObject(){

if (connection == null){

connection = new MyConnection();

}

}

}

Note thatdeclaration of the private constructor which tells that no other outside classes can directly instantiate this class. The only way to get a reference to the MyConnection object is to make a call to the static method MyConnection.getConnection().

1) static object connection is not initialized in the declaration itself.

2) initObject()creates a new object for the very first time only by making a comparison check.

Will the class works well in a multi-threaded environment?

certainly not.

private static void initObject(){
    synchronized (MyConnection.class) {              
        if (connection == null){
            connection = new MyConnection(); 
        }
    }
}


What is lazy and early loading of Singleton and how will you implement it?

lazy loaded singletons using plain old synchronization, simple but effective:

What is Double-checked locking (DCL)

double-checked locking is a design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. Only if the locking criterion check indicates that locking is required does the actual locking logic proceed.

class Foo {
    private Helper helper = null;
    public Helper getHelper() {
        if (helper == null) {
            synchronized(this) {
                if (helper == null) {
                    helper = new Helper();
                }
            }
        }
        return helper;
    }
 }

1. Check that the variable is initialized (without obtaining the lock). If it is initialized, return it immediately.

2. Obtain the lock.

3. Double-check whether the variable has already been initialized: if another thread acquired the lock first, it may have already done the initialization. If so, return the initialized variable.

4. Otherwise, initialize and return the variable.

J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly.

static volatile Singleton instance;

public static Singleton getInstance() {

if (instance == null) {

synchronized (Singleton.class) {

if (instance == null)

instance == new Singleton();

}

} return instance;

How do you prevent for creating another instance of Singleton using clone() method?

add a clone() method of our own, and throw a CloneNotSupportedException

public Object clone()
        throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }
 

How do you prevent for creating another instance of Singleton using reflection?

Throwing exception from constructor is an option.

How do you prevent for creating another instance of Singleton during serialization?

use of readResolve() method

private Object readResolve() {
    return Instance;
  }

Initialization on demand holder idiom (IODH)

Is a lazy-loaded singleton.

Idiom can be implemented in both single-threaded/serial and concurrent environments

Example

public class Something {
        private Something() {
        }
 
        private static class LazyHolder {
                private static final Something INSTANCE = new Something();
        }
 
        public static final Something getInstance() {
                return LazyHolder.INSTANCE;
        }
}

How it works

When the class Something is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition LazyHolder within it is notinitialized until the JVM determines that LazyHolder must be executed. The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCEbeing initialized by executing the (private) constructor for the outer class Something. Since the class initialization phase is guaranteed by the JLS to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstancemethod during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a serial operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized INSTANCEwithout incurring any additional synchronization overhead.

Enum-way

Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton"[9] for any Java that supports enums.

The use of an enum is very easy to implement and has no drawbacks regarding serializable objects.

Example :

public enum Singleton {
   INSTANCE;
 }

Noncompliant Code Example (Garbage Collection)

When a class is no longer reachable, it is free to be garbage collected. This behavior can be problematic when the program must maintain the singleton property throughout the entire lifetime of the program.

A static singleton becomes eligible for garbage collection when its class loader becomes eligible for garbage collection. This usually happens when a nonstandard (custom) class loader is used to load the singleton. This noncompliant code example prints different values of the hash code of the singleton object from different scopes.

  {
    ClassLoader cl1 = new MyClassLoader();
    Class class1 = cl1.loadClass(MySingleton.class.getName());
    Method classMethod = class1.getDeclaredMethod("getInstance", new Class[] { });
    Object singleton = classMethod.invoke(null, new Object[] { });
    System.out.println(singleton.hashCode());
  }
  ClassLoader cl1 = new MyClassLoader();
  Class class1 = cl1.loadClass(MySingleton.class.getName());
  Method classMethod = class1.getDeclaredMethod("getInstance", new Class[] { });
  Object singleton = classMethod.invoke(null, new Object[] { } );
  System.out.println(singleton.hashCode());

Code that is outside the scope can create another instance of the singleton class even though the requirement was to use only the original instance.

Because a singleton instance is associated with the class loader that is used to load it, it is possible to have multiple instances of the same class in the JVM. This typically happens in J2EE containers and applets. Technically, these instances are different classes that are independent of each other. Failing to protect against multiple instances of the singleton may or may not be insecure depending on the specific requirements of the program.

Compliant Solution (Prevent Garbage Collection)

This compliant solution takes into account the garbage collection issue described above. A class cannot be garbage collected until the ClassLoader object used to load it becomes eligible for garbage collection. An easier scheme to prevent the garbage collection is to ensure that there is a direct or indirect reference from a live thread to the singleton object that must be preserved.

This compliant solution demonstrates this technique. It prints a consistent hash code across all scopes. It uses the ObjectPreserver class based on [Grand 2002] and described in rule TSM02-J. Do not use background threads during class initialization.

  {
    ClassLoader cl1 = new MyClassLoader();
    Class class1 = cl1.loadClass(MySingleton.class.getName());
    Method classMethod = class1.getDeclaredMethod("getInstance", new Class[] { });
    Object singleton = classMethod.invoke(null, new Object[] { });
    ObjectPreserver.preserveObject(singleton); // Preserve the object
    System.out.println(singleton.hashCode());
  }
  ClassLoader cl1 = new MyClassLoader();
  Class class1 = cl1.loadClass(MySingleton.class.getName());
  Method classMethod = class1.getDeclaredMethod("getInstance", new Class[] { });
  Object singleton = ObjectPreserver.getObject();  // Retrieve the preserved object
  System.out.println(singleton.hashCode());