Sunday, September 12, 2010

Good Java Questions

What is a platform?
A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.

What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)

What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the package?
The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.




What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

Is Java code slower than native code?
Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.

How to make a class or a bean serializable?
By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.

How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.




How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static.

Which containers use a border layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.

How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.

What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.

Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.

What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.

What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.

What is the List interface?
The List interface provides support for ordered collections of objects.

How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What is the Vector class?
The Vector class provides the capability to implement a growable array of objects

What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
Is sizeof a keyword?
The sizeof operator is not a keyword.
What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
What is a native method?
A native method is a method that is implemented in a language other than Java.
How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.
Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
Which class is the superclass for every class.
Object
What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
Which Container method is used to cause a container to be laid out and redisplayed?
validate()
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.
What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).
What is a static method?
A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated

What is a protected method?
A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.
What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
What do heavy weight components mean?
Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.
Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
What are peerless components?
The peerless components are called light weight components.
What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.
If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.
What are the problems faced by Java programmers who don't use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.
What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference

Name Container classes. ?
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What is the List interface?
The List interface provides support for ordered collections of objects.
What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.

What is tunnelling?
Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get through firewall. In CS world, tunnelling means a way to transfer data.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

How you restrict a user to cut and paste from the html page?
Using javaScript to lock keyboard keys. It is one of solutions.

Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.

What is a Container in a GUI?
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects:
Objects allow procedures to be encapsulated with their data to reduce potential interference.
Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
The well-defined separations of interface and implementation allows constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism?
Polymorphism allows methods to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.

What is design by contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, post conditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

What are use cases?
A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust

Exception Handling Questions

Q: What do you mean by exception and error handling?
A: When a program encounters and un-expected situation from where it cannot continue the normal flow, it can break from the normal execution flow by throwing and exception or an error.
Q: What is the difference between an Error and an Exception?
A: An Exception is an unexpected scenario from which the program can recover but an error means that the program has encountered an unrecoverable problem.
Q: Can you give an example of an unrecoverable problem when error is thrown?
A: Yes, when a java program runs out of memory it is a problem from which the program cannot recover and OutOfMemoryError will be thrown.
Q: Does it mean that when error is thrown, we cannot catch it and continue execution?
A: We can catch errors, but it is not advised to do that because when error happens it means that some unrecoverable problem has happened. Even if we catch the error, we cannot guarantee the stability of the application and something else might fail.
Q: What are the different kinds of Exceptions?
A: Checked Exceptions and Unchecked Exceptions.
Q: What are runtime Exceptions?
A: Un Checked Exceptions are also known as Runtime Exceptions.
Q: What do you mean by Checked Exceptions?
A: Checked exceptions are those exceptions which have to be explicitly handled in the code.
Q: Can we create our own checked exceptions?
A: Yes, we just have to extend the Exception class or any of its sub classes (except RuntimeException)
Q: How can we create our own runtime exception?
A: We have to extend the RuntimeException class or any of its sub classes.
Q: How can we create our own Errors?
A: We have to extend the Error class.
Q: What are the different approaches of Exception handling?
A: We can use Try Catch block or we can declare the exception in the method definition’s throws clause
Q: Explain the difference between the two approaches of exception handling
A: We use the try catch clause where we want to process the exception and perform some action like displaying an error message. When an exception is caught using the catch clause, it will not be propagated to the caller.
We declare the exception in the throws clause of the calling method when the exception has to be propagated to the caller and the exception is supposed to be handled by the caller.
Q: What is finally?
A: Finally is also a block like catch block to be used with the try block. Control will come to finally block irrespective of whether exception was thrown or not.
Q: What is the difference between catch and finally?
A: When a catch block is used, we have to mention what exception has to be caught in the catch clause; where as in finally we need not mention anything. Code in the catch block is executed only when the exception is thrown whereas the code in finally is executed irrespective of whether exception was thrown or not.
Q: Can we have a try block without a catch block?
A: yes, then we must have a finally block. When try block is used, we must use either a catch block or a finally block or both.
Q: What happens when we use only try and finally block without a catch block?
A: When catch block is not used, the exceptions that are thrown will not be caught and the exception will be propagated to the caller, but before the exception is propagated, the code in the finally block will be executed.
Q: When do you use a catch block and when do you use a finally block?
A: We use a catch block when we want to handle the exception scenario. We use a finally block alone when we want to do some cleanup but at the same time propagate the exception to the caller. We use a finally block together with a catch block when we want to do something irrespective of what exception is thrown.
Q: what will happen if we return from the try block, will the finally block get executed?
A: yes, after the return statement in the try block is executed, the statements in the finally block will be executed before the control goes to the calling method.
Q: What happens when we have a return statement in the try block as well as in the finally block.
A: when we have return statement both in try and finally blocks, then first the return statement of try block gets executed, the before the method returns, the statements in the finally block will get executed and since there is return statement in finally also, that will also get executed and the value that will be returned to the caller will be the value returned from the finally block.
Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?
A: No.
Q: Can I have more than one catch block following a try block?
A: yes,
Q: what are the rules for having multiple catch blocks?
A:
1) Each exception can be caught only once.
2) The catch block for sub class exceptions should come before e the catch block for parent class exceptions for example, FileNotFoundException extends IOException, so the catch block for FileNotFoundException should come before the catch block for IOException.
Q: Suppose I have a class A that has a method X which throws FileNotFoundException. I have a class B that extends class A and the method X is overridden in B. In the ovverriden method X in class B can I throw IOException?
A: No, because FileNotFoundException is a subclass if IOException and in the overridden method X in class B we can throw only FileNotFoundException or any other exception that extends FileNotFoundException.
Q: Is the above rule logical?
A: yes, the above rule is logical because java supports runtime polymorphism and at runtime an object of type B can be assigned to a variable of type A because B extends A, and when the method X is called on the variable of type A, the compile only check that the calling method should either catch or declare the exception that method X in class A is throwing, and if the method X in class B throws IOException, and the caller is handling only FileNotFoundException, then the exception will escape unhandled.

Synchronization Questions

Q: what are the different ways of synchronization?
A: Synchronized method and synchronized block.
Q: How do you make a method synchronized?
A: A method can be made synchronized by using the synchronized keyword in the method declaration.
Q: What happens when multiple threads call a synchronized method?
When a thread enters a synchronized method, the object on which the method is called gets locked by that thread, so no other thread cannot call that or any other synchronized method on the same object.
Q: Do you mean to say that when a thread enters a synchronized method, no other thread can enter the same method or other synchronized methods on that class?
A: No, when a thread enters a synchronized method, only the object on which the method is called gets locked by that thread, but other objects instantiated from the same class are still not locked and methods on those instances can be called.
Q: What happens when I make a static method as synchronized?
A: Static methods are invoked directly on the class and not on object instances of the class, so when a thread enters a synchronized static method, the class itself gets locked by the thread and no other thread can enter any static synchronized methods on that class.
Q: When do you use synchronized blocks?
A: When synchronized method is used, the object on which the method is called gets locked by the thread. But, if you do not want that object to get locked, but you want some instance variable in that object to be locked, you go for synchronized blocks. Moreover, code in synchronized methods and block execute much slower that in non synchronized blocks and methods. Using synchronized blocks we can synchronize only the required portion of a method and thus improve performance.

Threads Questions

1) What are the two types of multitasking?

Ans : 1.process-based

2.Thread-based

2) What are the two ways to create the thread?

Ans : 1.by implementing Runnable

2.by extending Thread

3) What is the signature of the constructor of a thread class?

Ans : Thread(Runnable threadob,String threadName)

4) What are all the methods available in the Runnable Interface?

Ans : run()

5) What is the data type for the method isAlive() and this method is

available in which class?

Ans : boolean, Thread

6) What are all the methods available in the Thread class?

Ans : 1.isAlive()

2.join()

3.resume()

4.suspend()

5.stop()

6.start()

7.sleep()

8.destroy()

7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?

Ans :1. wait(),notify() & notifyall()

2. Object class

8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?

Ans : Synchronisation

9) What is the procedure to own the moniter by many threads?

Ans : not possible

10) What is the unit for 1000 in the below statement?

ob.sleep(1000)

Ans : long milliseconds

11) What is the data type for the parameter of the sleep() method?

Ans : long

12) What are all the values for the following level?

max-priority

min-priority

normal-priority

Ans : 10,1,5

13) What is the method available for setting the priority?

Ans : setPriority()

14) What is the default thread at the time of starting the program?

Ans : main thread

15) The word synchronized can be used with only a method.

True/ False

Ans : False

16) Which priority Thread can prompt the lower primary Thread?

Ans : Higher Priority

17) How many threads at a time can access a monitor?

Ans : one

18) What are all the four states associated in the thread?

Ans : 1. new 2. runnable 3. blocked 4. dead

19) The suspend()method is used to teriminate a thread?

True /False

Ans : False

20) The run() method should necessary exists in clases created as subclass of thread?

True /False

Ans : True

21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?

True/False

Ans : True

22) Which method waits for the thread to die ?

Ans : join() method

23) Which of the following is true?

1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method

2) Among wait(),notify(),notifyall() the wait() method only throws IOException

3) wait(),notify(),notifyall() & sleep() are methods of object class

1
2
3
1 & 2
1,2 & 3
Ans : D
24) Garbage collector thread belongs to which priority?

Ans : low-priority

25) What is meant by timeslicing or time sharing?

Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.

26) What is meant by daemon thread? In java runtime, what is it's role?

Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system

Wednesday, September 8, 2010

Hibernate Questions

Q. How will you configure Hibernate?

Answer:

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.


Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernate s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Q. What is a Session? Can you share a session object between different theads?

Answer:

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

&
public class HibernateUtil {
&
public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.


Q. What are the benefits of detached objects?

Answer:


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects?

Answer:

Pros:

" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.


Cons

" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

Answer

" Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.


Q. What is the difference between the session.update() method and the session.lock() method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.


Q. What are the general considerations or best practices for defining your Hibernate persistent classes?


1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.


3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.

4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.


Difference between session.save() , session.saveOrUpdate() and session.persist()?

session.save() : Save does an insert and will fail if the primary key is already persistent.

session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.
Insert data if primary key not exist otherwise update data.

session.persist() : Does the same like session.save().
But session.save() return Serializable object but session.persist() return void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.
For Example :
if you do :-
System.out.println(session.save(question));
This will print the generated primary key.
if you do :-
System.out.println(session.persist(question));
Compile time error because session.persist() return void.
Q. What is lazy fetching in Hibernate? With Example .
Lazy fetching decides whether to load child objects while loading the Parent Object.
You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
By default the lazy loading of the child objects is true.
This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object
.But in some cases you do need to load the child objects when parent is loaded.
Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
Example :
If you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects.
Parent Class : Employee class
Child class : Address Class
public class Employee {
private Set address = new HashSet(); // contains set of child Address objects
public Set getAddress () {
return address;
}
public void setAddresss(Set address) {
this. address = address;
}
}
In the Employee.hbm.xml file




In the above configuration.
If lazy="false" : - when you load the Employee object that time child object Adress is also loaded and set to setAddresss() method.
If you call employee.getAdress() then loaded data returns.No fresh database call.

If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true.
when you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects.
If you call employee.getAdress() then that time database query fires and return results. Fresh database call.

How to Integrate Struts Spring Hibernate ?
Details with code you can deploy in tomcat server and test .

http://www.techfaq360.com/tutorial/spring/struts_spring_hibernate.jsp

Step 1.
In the struts-config.xml add plugin

value="/WEB-INF/applicationContext.xml"/>



Step 2.

In the applicationContext.xml file
Configure datasourse

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@10.10.01.24:1541:ebizd

sa




Step 3.

Configure SessionFactory





com/test/dbxml/User.hbm.xml




net.sf.hibernate.dialect.OracleDialect





Step 4.
Configure User.hbm.xml













Step 5.

In the applicationContext.xml ? configure for DAO





Step 6.

DAO Class
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
private static Log log = LogFactory.getLog(UserDAOHibernate.class);

public List getUsers() {
return getHibernateTemplate().find("from User");
}

public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}

public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);

if (log.isDebugEnabled()) {
log.debug("userId set to: " + user.getId());
}
}

public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}
}

How to prevent concurrent update in Hibernate?
version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.

In hibernate you can perevent slate object updatation using version checking.

Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).

This way you can prevent slate object updatation.

Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Long getCampignId() {
return campignId;
}
private void setCampignId(Long campignId) {
this.campignId = campignId;
}

}

Step 2.
In the .hbm.xml file




CAMPIGN_ID_SEQ









Step 3.
Create a coulmn name "version" in the CAMPIGN table.

Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();


You can handle StaleObjectStateException() and do what ever you want.
You can display error message.

Hibernate autumatically create/update the version number when you update/insert any row in the table
Filter in Hibernate with Example?
Filter in Hibernate ------
USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE
public class User
{
private int id;
private String username;
private boolean activated;
public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
-----------------------------------------------------------------

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">













--------------------------------------------------------------------
Save and Fetch using filter example
User user1 = new User();
user1.setUsername("name1");
user1.setActivated(false);
session.save(user1);
User user2 = new User();
user2.setUsername("name2");
user2.setActivated(true);
session.save(user2);
User user3 = new User();
user3.setUsername("name3");
user3.setActivated(true);
session.save(user3);
User user4 = new User();
user4.setUsername("name4");
user4.setActivated(false);
session.save(user4);
All the four user saved to Data Base User Table.
Now Fetch the User using Filter..
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}
Guess the Result :
name2 name3

Because Filer is filtering ( only true value) data before query execute.
Difference between list() and iterate() i9n Hibernate?
If instances are already be in the session or second-level cache iterate() will give better performance.
If they are not already cached, iterate() will be slower
than list() and might require many database hits for a simple query.
Deleting persistent objects
Session.delete() will remove an object's state from the database. Of course, your application might still hold
a reference to a deleted object. It's best to think of delete() as making a persistent instance transient.
sess.delete(cat);
SQL statements execution order.
1. all entity insertions, in the same order the corresponding objects were saved using Session.save()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions, in the same order the corresponding objects were deleted using Session.delete()

Modifying persistent objects?
DomesticCat cat = (DomesticCat) sess.load( Cat.class, new Long(69) );
cat.setName("PK");
sess.flush(); // changes to cat are automatically detected and persisted To Data Base.

No need any session.update() call
Criteria Query Two Condition
Criteria Query Two Condition- Example








List of organisation where town equals to pune and status = "A".

List organizationList = session.createCriteria(Organization.class)
.add(Restrictions.eq("town","pune"))
.add(Restrictions.eq("statusCode","A"))
.list();
Equal and Not Equal criteria query.
Equal and Not Equal criteria query- Example







List of organisation where town equals to pune.
List organizationList = session.createCriteria(Organization.class).add(Restrictions.eq("town","pune")).list();
List of organisation where town not equals pune.
List organizationList = session.createCriteria(Organization.class).add(Restrictions.ne("town","pune")).list();
Cascade Save or Update in Hibernate ?
Cascade Save or Update - In one to Many- EXAMPLE
PROCESS_TYPE_LOV (PROCESS_TYPE_ID number, PROCESS_TYPE_NAME varchar) - TABLE
PROCESS (PROCESS_ID number,PROCESS_NAME varchar,PROCESS_TYPE_ID number)- TABLE

public class ProcessTypeBean {
private Long processTypeId;
private String processTypeName;

/**
* @return Returns the processTypeId.
*/
public Long getProcessTypeId() {
return processTypeId;
}
/**
* @param processTypeId The processTypeId to set.
*/
public void setProcessTypeId(Long processTypeId) {
this.processTypeId = processTypeId;
}
/**
* @return Returns the processTypeName.
*/
public String getProcessTypeName() {
return processTypeName;
}
/**
* @param processTypeName The processTypeName to set.
*/
public void setProcessTypeName(String processTypeName) {
this.processTypeName = processTypeName;
}
}

public class ProcessBean {
private Long processId;
private String processName = "";
private ProcessTypeBean processType;
public Long getProcessId() {
return processId;
}
/**
* @param processId The processId to set.
*/
public void setProcessId(Long processId) {
this.processId = processId;
}
/**
* @return Returns the processName.
*/
public String getProcessName() {
return processName;
}
/**
* @param processName The processName to set.
*/
public void setProcessName(String processName) {
this.processName = processName;
}
/**
* @return Returns the processType.
*/
public ProcessTypeBean getProcessType() {
return processType;
}
/**
* @param processType The processType to set.
*/
public void setProcessType(ProcessTypeBean processType) {
this.processType = processType;
}
}

table="PROCESS">

length="50" />



table="PROCESS_TYPE_LOV">

type="string" length="50" />

---------------------------------------------------------------------------------
Save Example Code -
ProcessTypeBean pstype = new ProcessTypeBean();
pstype.setProcessTypeName("Java Process");
ProcessBean process = new ProcessBean();
process.setProcessName("Production")
ProcessBean.setProcessType(pstype);

// session.save(pstype); -- This save not required because of in the mapping file cascade="save-update"
session.save(process); - This will insert both ProcessBean and ProcessTypeBean;
One To Many Bi-directional Relation in Hibernate?
Bi-DireCtional One to Many Relation- EXAMPLE
PROCESS_TYPE_LOV (PROCESS_TYPE_ID number, PROCESS_TYPE_NAME varchar) - TABLE
PROCESS (PROCESS_ID number,PROCESS_NAME varchar,PROCESS_TYPE_ID number)- TABLE

public class ProcessTypeBean {

private Long processTypeId;
private String processTypeName;
private List processes = null;

/**
* @return Returns the processes.
*/
public List getProcesses() {
return processes;
}
/**
* @param processes The processes to set.
*/
public void setProcesses(List processes) {
this.processes = processes;
}

/**
* @return Returns the processTypeId.
*/
public Long getProcessTypeId() {
return processTypeId;
}
/**
* @param processTypeId The processTypeId to set.
*/
public void setProcessTypeId(Long processTypeId) {
this.processTypeId = processTypeId;
}
/**
* @return Returns the processTypeName.
*/
public String getProcessTypeName() {
return processTypeName;
}
/**
* @param processTypeName The processTypeName to set.
*/
public void setProcessTypeName(String processTypeName) {
this.processTypeName = processTypeName;
}

}

public class ProcessBean {

private Long processId;
private String processName = "";
private ProcessTypeBean processType;

public Long getProcessId() {
return processId;
}
/**
* @param processId The processId to set.
*/
public void setProcessId(Long processId) {
this.processId = processId;
}
/**
* @return Returns the processName.
*/
public String getProcessName() {
return processName;
}
/**
* @param processName The processName to set.
*/
public void setProcessName(String processName) {
this.processName = processName;
}
/**
* @return Returns the processType.
*/
public ProcessTypeBean getProcessType() {
return processType;
}
/**
* @param processType The processType to set.
*/
public void setProcessType(ProcessTypeBean processType) {
this.processType = processType;
}
}

table="PROCESS">

length="50" />




table="PROCESS_TYPE_LOV">

type="string" length="50" />



class="com.bean.ProcessBean" />


One To Many Mapping Using List ?
WRITER (ID INT,NAME VARCHAR) - TABLE
STORY (ID INT,INFO VARCHAR,PARENT_ID INT) - TABLE
One writer can have multiple stories..
-------------------------------------------------------------
Mapping File...

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">













table="story">






-------------------------------------------------------
public class Writer {
private int id;
private String name;
private List stories;


public void setId(int i) {
id = i;
}

public int getId() {
return id;
}

public void setName(String n) {
name = n;
}

public String getName() {
return name;
}

public void setStories(List l) {
stories = l;
}

public List getStories() {
return stories;
}
}

---------------------------------------------------
public class Story {
private int id;
private String info;

public Story(){
}

public Story(String info) {
this.info = info;
}

public void setId(int i) {
id = i;
}

public int getId() {
return id;
}

public void setInfo(String n) {
info = n;
}

public String getInfo() {
return info;
}
}
----------------------------------------------------

Save Example ..
Writer wr = new Writer();
wr.setName("Das");

ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));
wr.setStories(list);

Transaction transaction = null;

try {
transaction = session.beginTransaction();
session.save(sp);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
throw e;
}
} finally {
session.close();
}
Many To Many Relation In Hibernate ?
Best Example..for Many to Many in Hibernate ..
EVENTS ( uid int, name VARCHAR) Table
SPEAKERS ( uid int, firstName VARCHAR) Table
EVENT_SPEAKERS (elt int, event_id int, speaker_id int) Table
-----------------------------------------------------------
import java.util.Set;
import java.util.HashSet;

public class Speaker{

private Long id;
private String firstName;
private Set events;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public Set getEvents() {
return this.events;
}

public void setEvents(Set events) {
this.events = events;
}

private void addEvent(Event event) {
if (events == null) {
events = new HashSet();
}
events.add(event);
}
}
--------------------------------------------------------
import java.util.Date;
import java.util.Set;

public class Event{

private Long id;
private String name;
private Set speakers;

public void setId(Long id) {
this.id = id;
}

public Long getId() {
return id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void setSpeakers(Set speakers) {
this.speakers = speakers;
}

public Set getSpeakers() {
return speakers;
}

}
--------------------------------------------------------------
Event.hbm.xml

"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">













------------------------------------------------------------------
Speaker.hbm.xml


"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">













----------------------------------------------------------------------
Save and Fetch Example
Event event = new Event();
event.setName("Inverse test");
event.setSpeakers(new HashSet());
event.getSpeakers().add(new Speaker("Ram", event));
event.getSpeakers().add(new SpeakerManyToMany("Syam", event));
event.getSpeakers().add(new SpeakerManyToMany("Jadu", event));
session.save(event); /// Save All the Data

event = (Event) session.load(Event.class, event.getId());
Set speakers = event.getSpeakers();

for (Iterator i = speakers.iterator(); i.hasNext();) {
Speaker speaker = (Speaker) i.next();
System.out.println(speaker.getFirstName());
System.out.println(speaker.getId());
}

How to set 2nd level cache in hibernate with EHCache?
When you are creating SessionFactory just add the below steps

String ecache = appHome+File.separatorChar+"ehcache.xml";
try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/

Then
sessionFactory = configuration.buildSessionFactory();

ECache.xml is like


maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>

maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>


ApplicationBean will be avilable in 2nd level cache
How to get JDBC connections in hibernate?
User Session.connection() method to get JDBC Connection.
How will you configure Hibernate?
Step 1> Put Hibernate properties in the classpath.
Step 2> Put .hbm.xml in class path ?
Code is Here to create session ...

package com.dao;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
*
* @author Satya Das
*/
public class HibernateUtil {
protected static final Logger logger=Logger.getLogger(HibernateUtil.class);
public static String appHome = "No";
private static SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal();
private static final ThreadLocal threadTransaction = new ThreadLocal();
/**
* Initialize Hibernate Configuration
*/
public static void initMonitor(){
logger.info("Hibernate configure");
try {
logger.info("appHome"+appHome);
String path_properties = appHome+File.separatorChar+"hibernate.properties";
String path_mapping = appHome+File.separatorChar+"mapping_classes.mysql.hbm.xml";
//String ecache = appHome+File.separatorChar+"ehcache.xml";

Properties propHibernate = new Properties();
propHibernate.load(new FileInputStream(path_properties));

Configuration configuration = new Configuration();
configuration.addFile(path_mapping);
configuration.setProperties(propHibernate);

/* try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/

sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
logger.error("Exception in initMonitor",ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* @return a Session Factory Object
*/
public static SessionFactory getSessionFactory() {
logger.info("Inside getSessionFactory method");
try {
if (sessionFactory == null) {
initMonitor();
}else {

//sessionFactory.getStatistics().logSummary();
}
} catch (Exception e) {
logger.error("Exception in getSessionFactory",e);
}
return sessionFactory;
}

/**
* @return Session . Start a Session
*/
public static Session getSession() {
Session s = (Session) threadSession.get();
logger.debug("session"+s);
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
logger.debug("session 1 $"+s);
}
return s;
}

/**
* Close Session
*/
public static void closeSession(){

Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
s.flush();
s.close();
}
}

/**
* Start a new database transaction.
*/
public static void beginTransaction(){
Transaction tx = null;
if (tx == null) {
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
}

/**
* Commit the database transaction.
*/
public static void commitTransaction(){
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null ) {
tx.commit();
}
threadTransaction.set(null);
} catch (HibernateException ex) {
rollbackTransaction();
throw ex;
}
}

/**
* Rollback the database transaction.
*/
public static void rollbackTransaction(){

Transaction tx = (Transaction) threadTransaction.get();
try {
threadTransaction.set(null);
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
tx.rollback();
}
} finally {
closeSession();
}
}
}
What are the Instance states in Hibernate?
transient
The instance is not, and has never been associated with any persistence context. It has no persistent identity
(primary key value).
persistent
The instance is currently associated with a persistence context. It has a persistent identity (primary key
value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate
guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).
detached
The instance was once associated with a persistence context, but that context was closed, or the instance
was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database.
For detached instances, Hibernate makes no guarantees about the relationship between persistent
identity and Java identity.
What are the core components in Hibernate ?
SessionFactory (org.hibernate.SessionFactory)
A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a
client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable
between transactions, at a process- or cluster-level.
Session (org.hibernate.Session)
A single-threaded, short-lived object representing a conversation between the application and the persistent
store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent
objects, used when navigating the object graph or looking up objects by identifier.
Persistent objects and collections
Short-lived, single threaded objects containing persistent state and business function. These might be ordinary
JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly
one) Session. As soon as the Session is closed, they will be detached and free to use in any application
layer (e.g. directly as data transfer objects to and from presentation).
Transient and detached objects and collections
Instances of persistent classes that are not currently associated with a Session. They may have been instantiated
by the application and not (yet) persisted or they may have been instantiated by a closed Session.
Transaction (org.hibernate.Transaction)
(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work.
Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several
Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction,
is never optional!
Architecture
Hibernate 3.0.2 9
ConnectionProvider (org.hibernate.connection.ConnectionProvider)
(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource
or DriverManager. Not exposed to application, but can be extended/implemented by the developer.
TransactionFactory (org.hibernate.TransactionFactory)
(Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/
implemented by the developer.
Extension Interfaces
Hibernate offers many optional extension interfaces you can implement to customize the behavior of your
persistence layer. See the API documentation for details.
What is a Hibernate Session? Can you share a session object between different theads?
Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

?
public class HibernateUtil {
?
public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
local.set(session);
}
return session;
}
}
addScalar() method in hibernate...
Double max = (Double) sess.createSQLQuery("select max(cat.weight) as maxWeight from cats cat")
.addScalar("maxWeight", Hibernate.DOUBLE);
.uniqueResult();

addScalar() method confim that maxWeight is always double type.

This way you don't need to check for it is double or not.
Difference between session.save() and session.saveOrUpdate()?
session.save() - Insert data into the table
session.saveOrUpdate()- Insert data if primary key not exist otherwise update
How are joins handled using Hinernate.
Best is use Criteria query
Example -
You have parent class
public class Organization {
private long orgId;
private List messages;
}
Child class
public class Message {
private long messageId;
private Organization organization;
}

.hbm.xml file




class="com.bean.Message" />










Get all the messages from message table where organisation id =

Criteria query is :
session.createCriteria(Message.class).createAlias("organization","org").
add(Restrictions.eq("org.orgId",new Long(orgId))).add(Restrictions.in("statusCode",status)).list();

you can get all the details in hibernate website.
http://www.hibernate.org/hib_docs/reference/en/html/associations.html
What is Hibernate proxy?
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.

Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. Very nice in simple cases with no object hierarchy. Typecasting and instanceof work perfectly on the proxy in this case since it is a direct subclass.
how to create primary key using hibernate?




increment generator class automatically generate the primary key for you.
How to Execute Stored procedure in Hibernate ?
Option 1:
Connection con = null;


try {
con = session.connection();

CallableStatement st = con
.prepareCall("{call your_sp(?,?)}");
st.registerOutParameter(2, Types.INTEGER);
st.setString(1, "some_Seq");

st.executeUpdate();

Option 2:






{ ? = call selectAllEmployees() }



code :

SQLQuery sq = (SQLQuery) session.getNamedQuery("selectAllEmployees_SP");

List results = sq.list();



1) Adv/Disadvantages of Hibernate:

a) Object - Relational mapping

b) The developer doesn't have to take into account the type of database he is coding for. The type of database can be changed by changing the dialect line in the configuration file.

c) Hibernate has caching.

d) Need to write less complex queries.

e) One has the choice as to how he wants the related objects of the object he wants to be loaded. (Fetching and join strategy)

f) Connection Pooling can be done by editing a few lines in the hibernate-cfg.xml file ..

c3p0 :- connection pool built in with Hibernate


hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/hibernate
hibernate.connection.username=root
hibernate.connection.password=
hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
hibernate.show_sql=false

hibernate.c3p0.max_size=1
hibernate.c3p0.min_size=0
hibernate.c3p0.timeout=5000
hibernate.c3p0.max_statements=100
hibernate.c3p0.idle_test_period=300
hibernate.c3p0.acquire_increment=2
Disadvantages:

slower in processing the queries than if the queries are used directly
adding the xml would cause portability problems

2) Explain Session Factory?

SessionFactory is Hibernate’s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory

3) Explain different type of fetch statements?

Fetching strategy is used by hibernate to retrieve associated objects if the Hibernate needs to go through to the association.
There are 4 types of fetching strategies:

fetch = join

Using the same 'select' statement the Hibernate will fetch the associated instance/ collection using outer join.

fetch = select

This is the default option. If there are 'n' associated objects to the one you requested then there would be 'n+1' select statements executed. If the lazy=true then these would executed only when the association is required.

fetch = subselect

A second select statement would be used to get all the related objects. If the lazy=true then this second select statement would be executed only when the association is called.

fetch=batch

It is an optimization strategy for fetch=select , where in using a list of primary or foreign keys one would pull out all instances/collection in a single select.

4) Explain lazy loading?

5) Explain object states?

Transient

Persistent

Detached:

Detached objects have a representation in database but changes done to the object won't be reflected to the database. A detached objects can be created by closing the session or by using the evict method of the session on the object. In order to reflect the changes in the object to the database the load,refresh,merge,update or save method on the object in any session.

6) Performance metrics in Hibernate?

sessionFactory.getStatistics

7) What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(…) returns null


8) Explain caching in Hibernate


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 Session Factory 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. This article focuses on second-level cache. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects.


Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:
EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.

Caching Strategies
Once you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:
Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
Read/write: Read/write caches may be appropriate if your data needs to be updated. They 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 strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
Transactional: This is a fully transactional cache that may be used only in a JTA environment.

9) Proxy pattern in Hibernate:

When an object contains another object and the loading is lazy then when the main object is created then it contains only a refernce to the object it contains. This reference is the proxy of the object it contains and this pattern is called proxy patters.

10) Interfaces in Hibernate:

Configuration,Session,Transaction and SessionFactory
11) Light weight ,Medium Weight and Heavy Weight mapping:

There are four levels of Hibernate Quality:

Pure: Stored Procedures

Light: JDBC

Medium:

Heavy:composition,inheritance, polymorphism, persistence by reachability



12) Difference between Hibernate and Ibatis:

In Ibatis Results of the SQL queries are mapped to the Objects where as in Hibernate the table is mapped to the object. Ibatis would be faster as it making use of the queries directly and is useful when you personally don't have much knowledge about the database.

13) What is NHibernate?

NHibernate is an Object Relational Mapping (ORM) solution for .Net.

14) Integrating Hibernate and Spring

1) Configure the SessionFactory in the 'spring.xml'


abcde/a.hbm.xml
abcde/b.hbm.xml


p:dataSource-ref="data.source.DataSource"
p:mappingResources-ref="abc.MappingResources"
p:hibernateProperties-ref="abc.HibernateProperties">



javax.transaction.TransactionManager





2) Configure the DataSource in the 'spring.xml'

class="org.springframework.jdbc.datasource.DriverManagerDataSource">


org.hsqldb.jdbcDriver


jdbc:hsqldb:mem:widgets


sa



3) Extend your DAO Implementation from HibernateDaoSupport

Tuesday, September 7, 2010

Types of Inner Classes

What are the different types of inner classes?

There are four different types of inner classes in Java. They are:

a)Static member classes , a static member class has access to all static methods of the parent, or top-level, class

b) Member classes, the member class is instance specific and has access to any and all methods and members, even the parent's this reference

c) Local classes, are declared within a block of code and are visible only within that block, just as any other method variable.

d) Anonymous classes, is a local class that has no name

final, finally and finalize

What is the differnce between final, finally and finalize?

final is used for making a class no-subclassable, and making a member variable as a constant which cannot be modified.

finally is usuall used to release all the resources utilized inside the try block.

All the resources present in the finalize method will be garbage collected whenever GC is called. Though finally and finalize seem to be for a similar task there is an interesting tweak here, usually I prefer finally than finalize unless it is unavoidable. This is because the code in finally block is guranteed of execution irrespective of occurance of exception, while execution of finalize is not guarenteed.finalize method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. Presumably the garbage collector will, like its civil servant namesake, visit the heap on a regular basis to clean up resources that are no longer in use. Garbage collection exists to prevent programmers from calling delete. This is a wonderful feature. For example, if you can't call delete, then you can't accidentally call delete twice on the same object. However, removing delete from the language is not the same thing as automatically cleaning up. To add to it, Garbage collection might not ever run. If garbage collection runs at all, and an object is no longer referenced, then that object's finalize will run. Also, across multiple objects, finalize order is not predictable. The correct approach to resource cleanup in Java language programs does not rely on finalize. Instead, you simply write explicit close methods for objects that wrap native resources. If you take this approach, you must document that the close method exists and when it should be called. Callers of the object must then remember to call close when they are finished with a resource.


    protected void finalize() throws Throwable {}
  • every class inherits the finalize() method from java.lang.Object
  • the method is called by the garbage collector when it determines no more references to the object exist
  • the Object finalize method performs no actions but it may be overridden by any class
  • normally it should be overridden to clean-up non-Java resources ie closing a file
  • if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class
protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}
  • any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
  • finalize() is never run more than once on any object