Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Spring MVC Framework Collection API Question - 2

This is the second set of questions that are generally asked for Collection Framework questions. These are a bit more advanced then the earlier set of questions.

Question 1: What is difference between ArrayList and LinkedList?
There are quiet a few difference between ArrayList and LinkedList:
  1. ArrayList uses a primitive array to store the values internally. However, LinkedList is made up of nodes where each nodes has three elements: value, pointer to next element and pointer to previous element.
  2. ArrayList implements the RandomAccess interface whereas LinkedList does not. RandomAccess is a marker interface which states that the implementation implements the fast algorithm to access the Nth element. So accessing Nth element is fast and takes constant-time for ArrayList whereas LinkedList has to scan the whole list to find the Nth element, hence making it slower for random access.
  3. Inserting and deleting an element at the start and end is faster in LinkedList as compared to ArrayList. While inserting an element in the LinkedList at the start and the beginning , we just need to create a node and assign the pointers whereas in ArrayList if you are inserting an element at the start, then first it will copy all the elements in a different list and then adds them after it, similarly while adding an element at the end means ArrayList will have to scan the whole list for inserting an element.
  4. LinkedList usually takes more memory than ArrayList as each node in the LinkedList will also store the next and previous pointers.
  5. ArrayList may also have issue if your list fills up quiet frequently as the ArrayList will create a new list with increased capacity and then copies all the elements whereas no such thing is required for LinkedList.
Question 2: Where will you use ArrayList and where will you use LinkedList?
If you have add elements at the start and end frequently or iterate over it for deleting elements then you should consider using LinkedList as it requires constant time for these operations and linear-time in ArrayList. If you have to access the positional elements then you should consider using ArrayList as it takes constant time for that and LinkedList take linear time for positional access.

Question 3: What is the difference between HashMap and HashTable?
The main difference is that HashTable is synchronised whereas HashMap is not. You need to provide external synchronisation if you want to synchronise the HashMap. Another difference is that HashTable does not allows null as keys or values whereas HashMap allow one null key and any number of null values.

Question 4: What is the difference between HashMap and TreeMap?
The basic difference is that in TreeMap objects are stored in an order decided either by the natural ordering of key or by the comparator that is defined at the the instantiation time of the TreeMap whereas HashMap does not guarantee any ordering. Since the elements are stored in an order, I think it is safe to say that the insertion of element in TreeMap will be slower as compared to HashMap whereas retrieval will be faster than HashMap.

Question 5: Explain how HashMap works or how the hashcode() and equals() method is used by the HashMap or how the get() method works in HashMap?
This question generally is the starting point for more complicated questions on HashMap. Basically what happens is when we call get(), put() method of HashMap. The HashMap uses the hashcode() method of the key to find the hashcode, then it uses its internal hashing mechanism to find the index of the correct "bucket" where the value might be stored. This bucket contains a list of Map.Entry objects in the form of a linked list. Once the bucket is identified, the map will traverse through the Map.Entry to find the exact key by using equals method, once found it will overwrite or return the value.

Question 6: How is HashSet implemented? or How will you implement the HashSet using HashMap?
Actually if you look closely on the HashMap methods there is already a set in the HashMap, they keySet. It has all the properties like no duplicates (HashMap does not allow duplicate keys). So, all you need to do is following, when you insert an object in HashSet, you insert the object as key in the HashMap and put the value as an EMPTY object. Same is the case when retrieving a value from HashSet, rather returning a value just return the key.

Question 7: Is Collection.synchronisedMap() is really thread-safe?
Question 8: What is the difference between ArrayList and Vector?
As per the Java API, the main difference between the ArrayList and Vector is that Vector is synchronised whereas ArrayList is not. The other difference is the way there size is incremented, Vector always doubles the size whereas ArrayList increases the size by half the initial capacity. So if there is a need for thread-safety is advisable to use Vector but since synchronisation takes a hit on the performance we may consider using the ArrayList and synchronise it using the Collections utility class.

Question 9: What are the mandatory  methods you should override while using TreeMap and why?

Spring MVC Framework Test Driven Development - using Eclipse

TDD is getting very important these days due to some of its benefits that most of the bugs are found at the development stage. Unit tests are already in place which gives you a better code coverage, more confident code and more importantly you always know that the addition of behaviour has not broken your previous code. Apart from that there are other benefits like you may end up getting a better design than you originally thought. It will also help in using a lot of patterns in your code, which may not be visible at the start.

I was going through some videos here, that explains how to use TDD in Java Development in Eclipse. The instructor has actually broken it down nicely and try to convince you of all the above points.

I liked some of his principle or things to remember, which are:
  • We are only doing one activity at a time
  • We can be doing any one activity of the four
    • Writing Test
    • Writing Production Code
    • Refactoring / updating / Cleaning Test code
    • Refactoring / updating / cleaning production code
  • We are only going to write production code when we have a failing test
  • When we add a test, earlier written test should not fail

Spring MVC Framework Basic Java Questions - 2

This is the second part of Basic Questions asked on Core Java. Please leave a comment if you think there is something wrong with an answer as it will help me greatly.
Question 1: What is data encapsulation in Java?
Data Encapsulation is the process of hiding the internal information from the external world. The information can only be manipulated using a set of operations exposed by the objects known as methods. This is also called as data hiding.

Question 2: What is the difference between Abstract Class and Interface?
Interface is a pure abstract class, means all the methods in interface are abstract whereas in Abstract class we can have non-abstract methods. All the methods in an interface are public by default, whereas Abstract class can have methods with other access modifier. All the method in an interface have only definition and no declaration, whereas an Abstract class can have method with the default implementation. All the member variables in the interface are final, whereas Abstract class can have non-final variables. An interface needs to be implemented using implements whereas an Abstract class needs to be extended using extends. A Java class can implement multiple interfaces but can only extend one Abstract class.

Question 3: Can I have an Abstract Class without any abstract method and vice-versa?
You can have an abstract class without any abstract method, if you don't declare a class as Abstract that have abstract methods, the class will give compilation error.

Question 4: What is the difference between Exception and Error?
Basically a user can recover from an exception at runtime but not from an Error. For example, a user program may recover from an FileNotFoundException, however, it wont be able to recover from an OutOfMemoryError. In other words, Exceptions are programmer generated and should be handled at the application level, whereas Errors are system generated and should be handled at the system level, if possible.

Errors are also a sub class of the Throwable, however we should try to avoid catching errors. If you have a catch Throwable, the block will also catch the Error, which is not a good practice.

Question 5: What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when the class is loaded using one of the following methods:
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.
Whereas, NoClassDefFoundError is encountered, when the JVM is trying to load the class as part of a normal method call or as part of creating a new instance using the new expression.

Question 6: Under what condition does finally block will not execute?
Finally block is a block in Java program, which gets executed most of the times. There are only few conditions under which the finally clock will not get executed.
1. If the Application executing the try or catch block exits by calling System.exit or by shutting down JVM.
2. If a thread executing the try or catch block is killed or interrupted, the finally block will not execute.

Question 7: Can you have a finally block without catch?
Yes, you can have finally block with the try statement, without a catch statement.

Spring MVC Framework Spring Interview Questions - 1

Spring is one of the most widely used framework in the Java/J2EE application. Almost all the job postings / consultancy requirements list Spring as one of the key skills. So it is no surprise that most of the interviews contains a wide list of Spring related questions. Here we will try to list some of the basic questions asked on the Spring Framework.
Question 1: What is Spring Framework?
Spring is an open source lightweight inversion of control application framework that supports the various aspects of application development.

Question 2: What are its features?
Spring has the following features:
  • Lightweight
  • Inversion of Control - A component lists its dependencies rather than looking for dependent objects.
  • Container - Contains and manages the lifecycle of various application components.
  • Aspect Oriented - Cross cutting concerns are handled separately through AOP module.
  • Transaction Management - Spring container provides an abstract layer of components to handle the transaction management thus allowing the developers to concentrate more on the business logic and allowing them to demarcate the transactions without worrying about the low-level issues, by providing plugable transaction managers. The spring transaction management can be run in a container less environment as well.  
  • JDBC Handling - Spring can be easily integrated with the Hibernate, JDO and iBATIS.
  • MVC Framework - Spring comes with a MVC framework as well which can use various presentation technologies like JSP, JSF, Velocity and Tiles etc. However, if you wish you to use some other MVC framework spring can be easily integrated with them as well.
Question 3: What is Inversion of Control / IoC?
Inversion of Control or IoC is a phenomenon used by frameworks to invert the control. Basically, in traditional programming the user / developer control the calling of a procedure, however when using IoC the framework controls the calling mechanism. Hence, saying simply that the framework calls us, we don't call it. Although the above statement state the calling of procedure, this can be used for any development term like instantiation etc. A better and elaborated discussion can be found here by Martin Fowler. Servlets, EJB, template method pattern can be stated as examples of Inversion of Control, in general they are Inverting the control. (Hint: Don't call us, we will call you.)

Question 4: How is Inversion of Control different from Dependency Injection?
Inversion of Control is a principle that is being followed in many frameworks, however dependency injection in one such patter that is built on top of IoC. IoC is generally followed in all framework as they are trying to invert some sort of control, however every framework may not provide you with dependency injection. In dependency injection it is the dependency creation control that is being inverted. In DI, rather than object creating the dependencies the framework will invert the control and inject dependencies. More on this can be found here.

Question 5: What pattern does Spring uses to create beans?
Generally there are lot of design patterns used in Spring to create beans. For Example,
  • Proxy interface, in case of AOP
  • Singleton, beans created in spring are singleton by default
  • Template method, in case of JdbcTemplate, JmsTemplate etc.
  • Abstract Factory pattern, is use to register and then instantiate various beans defined in the Configuration file.
Question 6: What are the ways to inject beans in Spring and which one should be used where?
In Spring beans can be inject by the setter method or by constructor. In Setter Injection, the bean is created using the default constructor or no-arg constructor and then the setter methods are called in to inject various beans. In Constructor Injection, the bean is created using the Constructed with a number of arguments and then these arguments can be inject while instantiation. Now the question arises which one should be used. IMHO I think we should use a combination of both. You should have a constructor with the "Required" arguments or collaborators and should have setter injection for dependencies which are optional. In this way, you are also making sure that you have all the required dependencies during its instantiation and optional properties can be set using setter injection. You can refer to the following blog at springsource to learn more about the above reason.

Question 7: What is JdbcTemplate in Spring DAO?
JDBCTemplate is the central class in the Spring DAO module, it has the template methods to open and close various resources, hence decreasing the programming errors. This class provides the basic workflow for a JDBC like opening the connection, preparing the statement , executing and then closing the connection thus leaving the application code to only provide the SQL and retrieve the results. It has methods for executing SQL queries, update statements and procedure calls. It also provides the methods for iterating over a result set. This class also catches SQL Exceptions and generates more informative exceptions defined in the Spring Exception hierarchy.



Spring MVC Framework Basic Java Questions - 1

This page contains the list of question that are generally asked in the Java General Questions. They can also be termed as questions asked on Basic Java Language.
Question 1: What is the difference between java.util.Date and java.sql.Date?
The main difference is that java.util.Date represents "date and time" stored upto a milisecond. However, java.sql.Date only stores data value which is required for the SQL DATE type. java.sql.Date has a java.sql.Time counterpart which stores only time.

Question 2: What is the difference between String, StringBuffer and String Builder?
  • String is immutable whereas StringBuffer/StringBuilder are not. It means it gives faster performance while update operations. 
  • StringBuffer is synchronised whereas StringBuilder is not.
  • Use String if you need immutability, use StringBuffer is you need mutability and thread-safety, use StringBuilder if you need mutability but not thread safety. 

Question 3: What are various visibility modifiers in Java and what is the difference between them?
There are four access modifiers : public, private, protected and default. There accessibility is as defined below:

public - Any class can access it directly.
protected - It is available to class, subclasses and package.
default or no-modifier: It has the package accessibility but is not available to subclasses.
private: This is only visible with the class itself.

Question 4: What is difference between .equals and "=="?
"==" checks whether the two references refer to the same instance whereas .equals check if the two different instances are equal.

Question 5: What is the relationship between .equals and hashcode()? or Why is it a good practise to either override both .equals() and hashcode() or none at all?
The relationship can be explained in simple way as, if two objects returns true for .equals() then their .hashcode() method must return the same value. However, if .hashcode() value returns same value .equals() may not return true, provided .hashcode() and .equals() uses the same fields for evaluation.

You should always override both these methods together because they should use the same fields to evaluate hashcode() and compare the two objects in .equals().

Question 6: Why is clone method "protected" in the Object class?
Default method in the Object class does not provide any implementation, so it does not make sense to make it public. Also, the object which needs to be cloned needs to implement Cloneable interface. Any object that wishes to be available for cloning can override this method and make it public.

Question 7: Is Generics a compile-time feature or runtime feature?
Generics are a compile-time feature, they help us to find some of the bugs at compile-time itself. Generics helps in ensuring the strong type checking. This information is not kept along with the compiled version of class.

Question 8: What is the use of serialVersionUId in Serializable class?
serialVersionUId is used in the serialization and de-serialization process. While serialization and de-serialization the serialVersionUId needs to be same. In case, the serialVersionUId is changed in a class the JVM will throw an "InvalidClassException". You should only change the serialVersionUId only,  when your serialization class is updated by some incompatible Java types changes to a serializable class. Please refer this for further explanation on serialVersionUId.

Question 9: What is the difference between Serializable and Externalizable?
When a class implement the serializable interface, the JVM will serialize and de-serialize the class variables by itself, however, if you want to change the way serialization is done you need to implement the Externalizable interface. When you implement the Serializable interface you dont need to implement any method the JVM will use reflection to serialize your class. However, if you implement Externalizable interface, you need to implement two methods readExternal() and writeExternal(). If you have implemented Serializable you can still control the serialization by writing two methods in your class namely, readObject() and writeObject().

Question 10: How can you control which fields should be serialized?
There are three exceptions to the Serialization process. They are:
1) Static fields are not serialized.
2) transient fields are not serialized.
3) Base class variables are only serialized if the Base class itself implement Serializable.

Spring MVC Framework Collection API Questions - 1

Java Collection Framework is one of the hot favourite among interviewers. The reason for that is any Java program uses Java Collection Framework intensively and any manager hiring for his team would like to see that you have basic and some advanced knowledge in the Collection API. Other reason that I find for interest in Collection Framework is that the questions will help in identifying whether the candidate knows how the various Data Structures are implemented in Java explaining his interest. 

In this post I will try to list some of the beginner to advanced level questions asked on the Collection Framework.


Question 1: What is the Java's collection API?
Java's Collection API is a unified architecture of interfaces, classes and algorithms that are required for representing and manipulation of Collections. For example, List, Map, Set and the like. Benefit of these classes is as follows:
1.        It reduces the programming effort for the developers.
2.        It increases the program speed and quality, since the Collection API provides the high-performance and high quality implementation of the data structure and the algorithms required for their manipulation.
2.        It increase software re-usability.
3.        Reduces efforts to learn and create basic data structures API’s

An excerpt from the Java's Collection Trail 



















Question 2: What are the basic interfaces in the Collection API?
Basic interfaces in the collection API are:

1. Collection: This is the parent interface and all other interfaces extend this interface.
2. Set: This is a core interface to represent a mathematical set, the basic thing about a set is it 
             does not have duplicate values and at most have one null value.
3. List: An ordered collection or sequence, the user of this interface has precise control over 
            where each element is inserted. The user can access each element by its index /  
            position. It differs from the set in the way, that it allows duplicates and null values.
4. Queue: This is a collection used to hold multiple elements prior to processing. Queues 
                  typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. 
                 Among the exceptions are priority queues, which order elements according to a  
                 supplied comparator or the elements' natural ordering. Whatever the ordering used, 
                 the head of the queue is the element that would be removed by a call to remove or  
                 poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other 
                 kinds of queues may use different placement rules.
5. Map: This is a collection of key-value pair. A Map cannot contain duplicate keys; each key 
              can map to at most one value.

The other two core interfaces are merely sorted versions of set and map.

1. SortedSet: This is a Set that maintains its elements in ascending order. Several additional  
                        operations are provided to take advantage of the ordering.
2. SortedMap: This is a Map that maintains its mappings in ascending key order.

Their hierarchy is depicted in the below diagram.


Question 3: What is the difference between Set and List?
The basic difference between a Set and List is that set does not allow duplicates and allows at most one null value. Also, List is an ordered collection of elements whereas set is an unordered collection of elements.

Question 4: Why doesn't Map interface extend Collection?
Theoretically, let us assume that Map extends Collection, So what exactly are the elements of this collection? The only answer to this is "key-value" pair. But you cannot really iterate over these elements without knowing the value of key. However, Map can be viewed as a collection of the keys, values, key-value pair or entrySets. Depicting this behaviour Map does provide the collection view method keySets(), values(), entrySets().

Similary, if the Collection interface extends Map interface, then what are the keys of these elements. There is no satisfactory example.While it is possible to view List as a possible map with the indices as the keys, this has a property that when you remove an element from the List, it changes the keys of the elements preceding it and hence the reason that we don't have Map view operations on the list.

Question 5: Why doesn't Collection extends Cloneable or Serializable interface?
The only answer I can think of is that it is rarely required to clone or serialize the whole collection. There are serializable / cloneable implementations of the Collection. So, if the user want to create a Cloneable/Serializable collection, he can create a generic collection and then can use addAll() to insert the collection in a cloneable / serializable collection implementation.

Question 6: What are the other useful interfaces in Collection Framework?
Other useful interfaces are:

  • Iteration : Enumerator, Iterator, ListIterator
  • Ordering: Comparable, Comparator
  • Performance: RandomAccess
Question 7: What is the difference between Enumerator, Iterator and ListIterator?
Property
Enumeration
Iterator
ListIterator
Number of method
2
3
9
Method names
hasMoreElements(), nextElement()
hasNext(), next(), remove().
add(), hasNext(), next(), hasPrevious(), previous(), nextIndex(), previousIndex(), set(),remove().
Access Direction
Forward-only
Forward only
Bi-directional
Summary
It provides a read only traversal of the collection. Legacy classes such as Vector and HashTable returns this
Iterator provides a method to remove an element from the iterator. Java Collection Framework classes return this.
It provides a bi-directional access on the collection and hence has methods to support it, like previous() and next(). It also allows the modification of elements using set() and add() operation.


Spring MVC Framework Multi threading Interview Questions - 1

Multi-threading is a concept that even some of the experience developers also find difficult to understand. If you are appearing for investment bank, insurance or healthcare technology services company, the chances are that you will be tested thoroughly on the multi-threading concepts. Depending upon your experience, the questions may vary from basic to advanced levels. There are generally a set of written questions as well on this topic, which I will try to compile very soon. So, here is the list of basic questions on multi-threading.

Question 1: What is difference between a process and thread?
A process is a single execution of a program whereas a thread is a single execution sequence within a process. A process may contain multiple threads. A thread is sometimes referred to as a lightweight process. Threads in a JVM share the same heap space. Hence, threads can share same object. Threads have their own stack space, this is how one invocation of a method and its local variables are kept thread safe. Heap is not thread safe and hence must be synchronised for thread safety. 

Question 2: What are the different ways of creating Threads?
1) By implementing Runnable
2) By Extending Thread class
3) By using Executor Framework

Question 3: Which of the above method should be use?
Generally we should try to create threads by implementing Runnable as it will come in handy, when we need multiple inheritance.

Question 4: What are Thread states possible?
Thread can have the following states:
1) Runnable - Thread has started and is waiting for the Thread Scheduler to pick and execute.
2) Running - Thread is actively executing the code.
3) Waiting - Waiting for some external event like finish a file I/O to finish.
4) Sleeping - Thread are put to sleep for a certain period of time and will become runnable when it wakes from sleeping duration.
5) Blocked on I/O or Synchronised: Blocked by an external call to I/O or waiting to acquire lock.
6) Dead - Thread has finished executing code.
Question 5: What is difference between sleep and wait method?
Sleep method is used to stop the thread execution for a certain period of time, whereas wait method is used to make the thread wait for some external event or woke up by another thread by calling notify() or notifyAll().

Question 6: What is the difference between notify() and notifyAll()?
notify() and notifyAll() methods are used to pass the control to another thread that might be in the waiting state. When we call notify() it only means that the call will wake up the thread next in line. However, by calling notifyAll() we are actually passing the control to a larger number of threads which in turn may again compete to get control.

Question 7: What is difference between Thread.start() and Thread.run()?
Thread.start() actually does the job of calling Thread.run(). If we call the Thread.run() directly then it would be a simple method call from the main thread. It will not cause the thread to run independently.

Question 8: When is the InvalidMonitorStateException is thrown? why?
This exception is thrown when we try to call wait(), notify() or notifyAll() methods on an object in your program where you do not have the lock on the object. InvalidMonitorStateException extends RuntimeException and hence we do not need to catch it.

Question 9: What happens if the static method is defined as synchronized?
Executing such a method would mean that the thread has acquired a "Class" level lock, which means other threads cannot executed any other "static synchronized" method. This is different then the instance method synchronization in the way that two threads can execute the same synchronized instance method as long as they are executing it on the different instance of the object.

Spring MVC Framework Singleton Design Pattern Questions

Singleton Design Pattern is the basic design pattern that most of the developers seems to learn at the very early stages of their career (including me). So it is natural that there are lot questions that interviewers asked in order to see whether the person has just crammed up the definition or actually knows how to write it as well. Also, the implementation of this pattern has also changed a lot over time and a thorough knowledge of the same would mean that the person is also up to date with the new techniques.
Question 1: Explain Singleton Design Pattern?
Singleton Design Pattern means there is only one instance of an object in the Application / per classloader.

Question 2: What are the things required to implement a Singleton class?
Singleton class should have a private constructor and there is only way to create singleton instance.

Question 3: How do you implement Singleton?
In order to create a Singleton please see below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 4: Is the above class thread-safe?
The problem with the above class is that if two methods execute the getInstance() method, both of them might be able to create an instance and hence violating the Singleton condition. In order to achieve thread-safety, we can make the getInstance() method synchronized. as below:

     public class SingleTon {
private static SingleTon INSTANCE;

private SingleTon() {
}

public synchronized static SingleTon getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingleTon();
}

return INSTANCE;
}
}
Question 5: In the above solution synchronizing the static method will give you a class level lock and hence have performance impact? How can you remove that?
In order to remove the synchronizing we can have a static field instantiating the Singleton as below:

     public class SingleTon {
private static final SingleTon INSTANCE = new SingleTon();

private SingleTon() {
}

public static SingleTon getInstance() {
return INSTANCE;
}
}
The problem with the above class is that if your Singleton class have lot of constructs you might end up creating them even though you may not need them. So above should only be used if the Singleton is not very heavily loaded.This type of initialization is also known as Eagerly Initialization whereas the above initialization is known as Lazy Initialization.

Question 6: How to improve the above solution incase the class is heavily loaded?
In that case we would like to delay the instantiation process as below, by using an inner static class:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 7: How do you prevent the Singleton class creation using reflection?
One way to do that is to throw an exception from the Constructor as follows:
public final class SingleTon {
private static class SingleTonHolder {
private static SingleTon INSTANCE = new SingleTon();
}

private SingleTon() {
if(SingleTonHolder.INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
return SingleTonHolder.INSTANCE;
}
}
Question 8: Is there any other method that can be used to create a Singleton class?
Other method that can be used to create a Singleton class is the enum method, this solution is only applicable post Java 1.5. This is possible using Enum as:
public enum SingleTon3 {
INSTANCE;
// Other instance methods.
}
The advantage of using this is that, Java Memory Model guarantees that there will a single instance of the Enum and Enums are thread-safe as well.

Question 9: What do you understand by the double checked locking in Singleton pattern?
Double checked locking means that the INSTANCE is checked for NULL twice, before and after acquiring lock. Remember that it is only possible after Java 5, with the better handling of volatile fields. This may not work before Java 5.
     public final class SingleTon {
private SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}
}
Question 10: How do you avoid a Singleton being created by serialization?
This problem occurs when your Singleton implements Serializable. The readResolve() method will always return a new instance of the class, just like Constructor. In order to avoid this you can override the readResolve() method to return your INSTANCE as:
     public final class SingleTon {
private volatile SingleTon INSTANCE;

private SingleTon() {
if(INSTANCE != null) {
throw new IllegalStateException("Already Instantiated");
}
}

public static SingleTon getInstance() {
if(INSTANCE == null) {
synchronized(this) {
if(INSTANCE==null) {
INSTANCE = new SingleTon();
}
}
}

return INSTANCE;
}

private Object readResolve(){
return INSTANCE;
}
}
This can even become more complex if your Singleton starts to manage states, as then the states have to be transient. This problem can also be handled by Enums, as the serialization is handled by the JVM.
Question 10: Why should you avoid Singleton anti-pattern or why is Singleton is an anti-pattern?
  1. In order to use Singleton we need to call getInstance(), which makes them tightly coupled to the calling object and hence makes them hard to mock while testing.
  2. They maintain their state during the lifetime of the application and hence makes unit testing difficult as you may need to execute your Junit in an order. This voids the basic principle of Unit testing that the tests should be independent of each other.
  3. They violate the Single Responsibility Priniciple, as they manage the creation and lifecycle themselves.
  4. They are generally used as a global variable and creating global variable just to avoid passing them around is a code smell. 

Spring MVC Framework Hibernate Questions -1

Hibernate is an ORM tool that is used by various applications to reduce the effort of writing Database interaction code. It is a kind of becoming de-facto for various database tasks. So it becomes important for most of the organisation in the Java JEE space that there development team is well versed with this technology. Here I would try to list various questions that might be asked on Hibernate technology.


Question 1: What is ORM?
ORM is object relational mapping. It is the automated process for persisting Java objects to relational database.

Question 2: What are the ORM levels?
Main ORM levels are:
  • Pure relational (Stored procedure)
  • Light object mapping  (JDBC)
  • Medium object mapping 
  • Full object mapping (Composition, inheritance, polymorphism)
Question 3: What is Hibernate?
Hibernate is a pure Java ORM tool that maps the POJO's to the relational database tables using (XML) configuration files. It helps in reducing the effort of a Java Developer to produce the code that perfomrs relational database tasks.

Spring MVC Framework Mutli Threading Question Written - 1

Question : There are three threads, which can print an assigned array as below:

            Thread1  - {1,4,5}
            Thread2  - {2,5,7}       
            Thread3  - {3,6,9}

Write a program that print the output so that the output is always 1,2,3,4,5,6,7,8,9? Also, make it extendible so that the same logic can be applied to more number of threads.

Solution:


public class MultipleThreads {
public static void main(String args[]) {
//same instance of printer that is shared among the threads
Printer printer = new Printer(3); // three is the maximum number of threads.

NumberThread thread1 = new NumberThread(new Integer[]{1,4,7}, 1, printer); // First arguement is the array, second is the Thread number, printer is the shared instance
NumberThread thread2 = new NumberThread(new Integer[]{2,5,8}, 2, printer);
NumberThread thread3 = new NumberThread(new Integer[]{3,6,9}, 3, printer);

thread1.start();
thread2.start();
thread3.start();

}
The NumberThread class looks like:
   public class NumberThread extends Thread {

private Integer[] integerArray;
private int threadNumber;
private Printer printer;

//Constructor
public NumberThread(Integer[] array, int thread, Printer printer) {
this.integerArray = array;
this.threadNumber = thread;
this.printer = printer;
}

@Override
public void run() {
int index = 0; // index to keep track that all the elements are traversed
while(index < integerArray.length) {
synchronized(printer) {
while(!printer.myTurn(this.threadNumber)) {
try {
printer.wait();
} catch (InterruptedException ie) {
}
}
printer.print(integerArray[index]);
index++;
printer.notifyAll();
}
}
}

}
The Printer class is as follows:
  public class Printer {
private int maxThreads;
private int currentThread = 1;

public Printer(int numberOfThreads) {
this.maxThreads = numberOfThreads;
}

public void print(int number) {
// print the number
System.out.println(number);
currentThread = (currentThread % maxThreads) + 1;
}

public boolean myTurn(int threadNumber) {
return currentThread == threadNumber;
}
}
In order to extend the above logic, it can be extended for the number of elements in array and the number of threads that needs to be executed in a one-one-by kind of execution.

Please leave a comment if you think there is a problem in the above code or if there is any modification / optimization that can be done.

Spring MVC Framework Spring Interview Question - 2

This is the second set of questions that are generally asked during the interviews on Spring Framework. Some of these are advanced level questions like on the MVC architecture.

Question 1: What is BeanFactory?
Bean Factory is a factory class that contains the definition of multiple beans in itself, it can instantiate various beans when asked by the client. It has the capabilities to perform two major task during this process.
  • It is able to resolve the association between collaborating objects as the beans are instantiated. It in term removes the burden of the the configuration from the bean itself or from the calling client.
  • It can also call the various life cycle methods of beans and can calls the instantiation and destruction methods.
Question 2: What is ApplicationContext?
ApplicationContext is also like BeanFactory, the difference being that BeanFactory can only be created programmatically  whereas ApplciationContext can be created declaratively using ContextLoaders, for example a ContextLoaderListener. Apart from being able to perform the lifecycle control just like BeanFactory it can also load the various text message resources, file resources and can also pass the various events to beans that are registered as Listeners.

Question 3: What is Dependency Injection and Why is it becoming the de-facto standards for applications?
Dependency injection is the mechanism provided by framework where in the framework is responsible for creating the various dependencies and injecting them rather than the object creating the dependency. It becoming quite popular these days for the simple reason that it provides a loose coupling between various components. So, tomorrow if one of the dependency  changes rather then the whole application getting effect all the programmers need to do is just change the configuration as long as the changed bean also follows the same "contract" / interface as the previous one.

Question 4: What is the Spring's MVC architecture? or How does a web Request flows through Spring MVC?
Spring MVC architecture consists of the following things:
  • DispatcherServlet
  • LocaleResolver
  • MultipartResolver
  • ThemeResolver
  • HandlerMappings
  • Controller
  • ResultToViewNameTranslator
  • ViewResolver
The above components works as following to serve the request.
  • The DispatcherServlet receives the request from client
  • It uses the LocaleResolver to load any properties based on the Locale of the generated request.
  • It then uses the ThemeResolver to find any specific theme / template that might be used for that particular locale.
  • Then it find out whether the request has a multipart mime type then it initialises the file upload classes.
  • Then it uses the HandlerMappings to find the correct controller, where it uses the Model / Service Layer to execute the business logic. Before calling the controller method it has the capability to call the Pre adn Post Controller interceptor, which largely work as filters. 
  • Then it calls the ResultToViewNameTranslator to find the correct view.
  • Then the controller populates the Model and uses the ViewResolver to find the next view. It then combines the Model and the View to prepare the view, which is then passed to the container to return as Response.
Question 5: What are the main class in the Spring MVC architecture?
The main classes in the MVC architecture are as follows:
  1. DispatcherServlet
  2. MultipartResolver
  3. LocaleResolver
  4. ThemeResolver
  5. HandlerMapping
  6. HandlerAdapters
  7. HandlerExceptionResolver
  8. ResultToViewNameTranslator
  9. ViewResolver
Question 6: What is the typical lifecycle of a bean in the bean factory container?
Bean lifecycle in a bean container is as follows:
  • BeacFactory reads the bean definition from the xml configuration file.
  • BeanFactory instantiate the bean.
  • Using the dependency injection bean factory populates all the bean properties as specified in the bean definition.
  • If the bean implements BeanNameAware interface, then it calls the setBeanName() method passing the bean id.
  • If the bean implements BeanFactoryAware interface, then it calls the setBeanFactory() method passing an instance of itself.
  • If the bean has any BeanPostProcessors associated with itself it will call the postProcessBeforeTheInitialization() method.
  • If any init method is declare it will call that method and initialize the bean.
  • Finally if any BeanPostProcessor is associated with the bean then it will call the postProcessAfterInitialization().
Question 7: What are various Bean scopes available in Spring?
Spring supports the following scopes:
  • singleton - This is the default scope of a spring bean, it means the same instance is available through out the application
  • prototype - This means that the bean act as a template and a new instance will be injected for different beans.
  • request - The bean definition is available till the scope of an HTTP request. This is only applicable in case of the web-aware application context.
  • session - The bean is available till the scope of HTTP session. This is only applicable in case of the web-aware application context.
  • global-session - The bean is available till the scope of a global HTTP session. This is typically applicable in case of portlet context.
Question 8: Why is Spring MVC better than Struts ?