Wednesday, October 26, 2016

Java Garbage Collection

Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.


unused objects are considered to be any instances that cannot be reached by a live thread or for circularly referenced instances that cannot be reached by any other instances.
The basic process are :
  1. Marking : garbage collector identifies which objects are used and which are unused.
  2. Deletion: remove unused object and pointer to free space.
  3. Compacting : To improve performance move used object together so that there is no gap among them.   
Having to mark, delete and compact all the objects in a JVM is inefficient. empirical analysis of applications has shown that most objects are short lived and fewer objects remain allocated over time hence JVM Heap is broken into smaller parts as Young Generation, Tenured/ Old generation, Permanent Generation(removed in java 8).

Young Generation: This part of the heap is further divided into Eden Space, First survivor space, and Second survivor space.
Old Generation: long survived object are stored after minor GC.  
Permanent Generation: contain metadata of class and methods  required by JVM.

Few Important Terms:
Minor GC: minor GC triggered when JVM unable to allocate memory for new object. Generally when Eden space is full.
Major GC: happens for the Old Generation or aged Objects.
Stop The World : All minor/major garbage collections are "Stop the World" events means that all application threads are stopped until the operation completes.

Generational Garbage Collection Process:
  1. New objects are allocated to the eden space.
  2. When eden space is full minor GC triggered referenced object moved to first survivor space and eden space is cleared. During each minor GC aged object from first survivor space moved to second survivor space.
  3. As minor GCs continued age of the survived objects incremented and at certain threshold they moved to Old generation space. a major GC will be performed on the old generation which cleans up and compacts that space.
Garbage Collectors:
The Java HotSpot VM includes three different types of collectors, each with different performance characteristics.

  1. Serial Collector : Uses a single thread to perform GC hence it cannot take advantage of multiprocessor useful for application with small data sets. The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC.

  1. Parallel Collector: known as the throughput collector performs collections in parallel, which can significantly reduce garbage collection overhead and intended for applications with medium-sized to large-sized data sets that are run on multiprocessor or multithreaded hardware. default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseParallelGC.

  1. Concurrent collector :  Java Hotspot VM has two mostly concurrent collectors are Concurrent Mark Sweep(CMS Collector) and Garbage-First Garbage Collector(java 8).

Characterize the actual different primary garbage collectors:

Young generation collectors

  1. Serial collector (enabled with -XX:+UseSerialGC)
  2. PS Scavenge (enabled with -XX:+UseParallelGC)
  3. ParNew (enabled with -XX:+UseParNewGC)
  4. G1 Young Generation (enabled with -XX:+UseG1GC)

Old generation collectors

  1. MarkSweepCompact (enabled with -XX:+UseSerialGC)
  2. PS MarkSweep (enabled with -XX:+UseParallelOldGC)
  3. ConcurrentMarkSweep (enabled with -XX:+UseConcMarkSweepGC)
  4. G1 Mixed Generation (enabled with -XX:+UseG1GC)

All of the garbage collection algorithms except ConcurrentMarkSweep are stop-the-world, it tries to do most of it's work in the background and minimize the pause time, but it also has a stop-the-world phase and can fail into the MarkSweepCompact which is fully stop-the-world.

Reference :
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Saturday, July 16, 2016


Spring Transaction
Transaction comprises of a unit of work against a database. Transaction provides “all or noting” preposition unit of work performed entirely committed or rollback.

Unit of work: consider to transfer account balance from account A to account B we have to debit account A and credit account B and this is a unit of work performed to do transfer.

Acronym ACID describes the nature or properties for transaction.

  •   Atomic: All of the operations in a transaction happen or none of them happen.  
  •   Consistent: After a successful or failed transaction system is left in a consistent state.
  • Isolation: it is about concurrent read write if two or more transaction progressing at time. 
  •  Durable: after a successful transaction data is persisted permanently.  

Transaction attributes:
  • Propagation
1.     PROPAGATION_REQUIRED: transaction already exists then the code will use it otherwise a new transaction is created. This is the default.
2.     PROPAGATION_SUPPORTS: transaction exists then the code will use it, but the code does not require a new one.
3.     PROPAGATION_MANDATORY: Participates in an existing transaction, however if no transaction context is present then it throws a TransactionRequiredException.
4.     PROPAGATION_REQUIRES_NEW: new transaction and if an existing transaction is present then it is suspended. When the new transaction is complete then the original transaction resumes.
5.     PROPAGATION_NOT_SUPPORTED: operations needs to be performed non-transitionally.
6.     PROPAGATION_NEVER: code cannot be invoked within a transaction. if an existing transaction is present then an exception will be thrown.
7.     PROPAGATION_NESTED: code is executed within a nested transaction if existing transaction is present; if no transaction is present then a new transaction is created.
  • Isolation
1.     ISOLATION_DEFAULT: Use the isolation level of the underlying database. This is the default.
2.     ISOLATION_READ_UNCOMMITTED:  dirty reads, phantom reads and non-repeatable reads.
3.     ISOLATION_READ_COMMITTED: prevents dirty reads but allows phantom reads and non-repeatable reads.
4.     ISOLATION_REPEATABLE_READ: prevents dirty reads and non-repeatable reads but allows phantom reads.
5.     ISOLATION_SERIALIZABLE: prevents dirty reads, non repeatable reads and phantom reads.

Dirty Reads- Dirty reads occur when transaction B reads data that has been modified by transaction A but not committed. The problem occurs when transaction A rollbacks the transaction, in which case the data read by transaction B will be invalid.

Non Repeatable Reads- Non-repeatable reads happen when a transaction fires the same query multiple times but receives different data each time for the same query.

Phantom Reads - Phantom reads occur when the collection of rows returned is different when a same query is executed multiple times in a transaction.

  • Read only: The read only attribute specifies that the transaction is only going to read data from a database. by default false.
  • Rollback rule: specify that transactions roll back on certain exceptions and do not rollback on other exceptions.By default RuntimeException.
  • Timeout: Timeout specifies the maximum time allowed for a transaction to run then rolled back.

Spring Transaction supports:

  • It offers both programmatic and declarative transaction.
  • Declarative transaction can be used in stand-alone application unlike EJB.
  • Support wide range of transactional manager,.
  • Spring transactions are good at application using single database. I multiple databases access required have to use XA transaction of JTA.

Spring transaction managers: soring does not manage transaction directly rather delegate the responsibility to configured platform specific transaction manager.

JDBC
DataSourceTransactionManager
Hibernate
HibernateTransactionManager
JDO
JdoTransactionManager
JTA
JtaTransactionManager
JPA
JpaTransactionManager
















x

Wednesday, November 6, 2013

JAVA Collection Framework

Where will you use ArrayList and where will you use LinkedList?
-------------------------------------------------------------------
ArrayList is faster for iteration and LinkedList is faster for insertion and deletion. So if the list will more frequently be read or searched than modifying
it then ArrayList is the better choice and the list will be modified more frequently than reading or searching then LinkedList is a better choice.

What is difference between array and ArrayList?
------------------------------------------------
Array is a fixed length data structure but ArrayList is resizable Collection.

Array elements must be of same type but ArrayList can contain different types of elements.

Array can contain premitive types but ArrayList cannot contain premitive types.

Arrays cannot use Generics but ArrayList can use Generics.

What is fail-fast, fail-tolerant and fail-safe property?
--------------------------------------------------------

Fail-fast property is to immediately respond to operations that might lead to failure or exception.

Fail-tolerant property allows to system to continue in case failures rather than completely stopping the system.

Fail-safe property assumes that the failure is safe for the system.

What is the difference between Iterator and ListIterator?
----------------------------------------------------------

ListIterator interface extends the interface Iterator.
ListIterator can be used only to iterate a List but Iterator can be used to iterate a Set or a List.
Iterator allows only forward traversal but ListIterator allows both forward and backward traversal.
ListIterator provides additional methods like add() , set()

What is the difference between Enumeration and Iterator interface?
--------------------------------------------------------------------
Enumeration was created to traverse through the elements of a Vector and the keys where as  Iterator is created to traverse through the elements of a Collection.
Enumeration is faster than Iterator.
Enumeration uses less memory than Iterator.

What is the difference between ArrayList and Vector?
-----------------------------------------------------
All the methods of Vector are synchronized but the methods of ArrayList are not synchronized
he Enumeration returned by Vector’s elements() method is not fail-fast whereas ArraayList have method to return Iterator.

What is the difference between List and Set?
-------------------------------------------
List is an ordered collection which allows duplicate elements but Set is an unordered collection which does not allow duplicate elements.

How a Set prevents inserting duplicate elements?
-------------------------------------------------
Set uses both equals() and hashCode() method to check for the duplicates. The equals() and hashCode() contract must be satisfied to prevent inserting duplicate
elements into a Set.

Which is a better choice in terms of Insertion and Iteration between List and Set?
-----------------------------------------------------------------------------------
In terms of Insertion List is faster than Set because List can directly add an element at the end but Set needs to perform a sequential check for a duplication
before adding. This duplication checking makes Set slower than List.

In terms of Iteration List is faster because it supports indexed access


What is the difference between HashSet and TreeSet?
-----------------------------------------------------
HashSet is not sorted but TreeSet is sorted by the natural ordering defined in the Comparable object’s compareTo() mothod or it can be created using the TreeSet
constructor using a Comparator.

HashSet is faster than TreeSet in case of iteration and insertion.

Can a null element be added to a HashSet or TreeSet?
-------------------------------------------------------
HashSet allows inserting null into it only once. TreeSet allows inserting null into it multiple times or disallows based on the definition of comparing of the
objects in Comparable.compateTo() or Comparator.compare() method.

What is the effect of implementing equals() but not implementing hashCode() in case of a List and Set?
-------------------------------------------------------------------------------------------------------
No impact will be observed in case of insertion and selection for Vector, ArrayList and LinkedList.

Duplicate elements will be inserted into a Set. If we search using the actual object reference that was used to insert only then the object will be found in HashSet
and LinkedHashSet.

If hashCode() is not overridden but equals() is overridden then Set will be able to distinguish duplicates?
-------------------------------------------------------------------------------------------------------------
The default implementation provided by the Object.hashCode()returns distinct integers for distinct objects because it returns the internal address of the object.
Hence if two objects are equal according to the equals() method even then the hashCode of them will be different, which is a violation of the hashCode contract and
the Set will consider them as different objects.


Explain the methods present in Queue interface?
----------------------------------------------------
offer(): Inserts an element if possible, otherwise returns false. This differs from the Collection.add() method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity or “bounded” queues.

remove(): Returns the head of this Queue and if this queue is empty then throws NoSuchElementException. It removes the head of this Queue.

element(): Returns the head of this Queue and if this Queue is empty then throws NoSuchElementException. It does not remove the head of this Queue.

peek(): Returns the head of this Queue and if this Queue is empty then returns null. It does not remove the head of this Queue.

poll(): Returns the head of this Queue and if this Queue is empty then returns null. It removes the head of this Queue.


What is PriorityQueue?
---------------------------
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator. A priority queue does not permit null elements
also does not permit insertion of non-comparable objects

The head of this queue is the least element with respect to the specified ordering.

 What is ConcurrentHashMap?
--------------------------------
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates.



What are the default initial capacities of Vector, ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, Hashtable, HashMap, LinkedHashMap and TreeMap?
---------------------------------------------------------------------------------------------------------------------------------------------------------
The default initial capacity of a Vector is 10 and it increases by 100%.
1
   
newCapacity = oldCapacity * 2

The default initial capacity of an ArrayList is 10 and it increases by 50%.
1
   
newCapacity = (oldCapacity * 3)/2 + 1

LinkedList starts with a single LinkedList.Entry reference which is a private static inner class.

The internal data structure of a HashSet is a HashMap whose default initial capacity is 16 with load factor of 0.75.

The internal data structure of a LinkedHashSet is a LinkedHashMap whose default initial capacity is 16 with load factor of 0.75.

The internal data structure of a TreeSet is a TreeMap that starts with a single TreeMap.Entry reference named root.

The default initial capacity of a HashTable is 11 with load factor of 0.75.
1
   
newCapacity = oldCapacity * 2 + 1

The default initial capacity of a HashMap is 16 with load factor of 0.75.

The default initial capacity of a LinkedHashMap is 16 with load factor of 0.75.

TreeMap starts with a single TreeMap.Entry reference named root.

While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?
----------------------------------------------------------------------------------------------------------------------

Collections.unmodifiableCollection() method returns a read only collection and any attempt to modify the collection throws an


What are different ways to iterate over a list? Which one is faster?
-----------------------------------------------------------------------
There are two ways to iterate over a list. We can use an iterator or we can use a for loop. Iterating using a for loop is faster because ArrayList is
internally an array so it provides indexed access and thus the values will be directly accessed as per the index.UnsupportedOperationException exception.

What are different ways to iterate over a Map? Which one is faster?
-----------------------------------------------------------------------

Map interface provides three different collection views: keySet(), values() and entrySet().

The keyset() method returns a Set of the keys and the get() method can be used to get the value. The values() method returns a Collection of only the values so
keys are not available.

The entrySet() method returns a Set of Map.Entry objects which contains both key and value. We can iterate over these views either by an Iterator or by a For loop.

Collection interface provides toArray() method so Map can be converted to an array and the array can be iterated. It provides three additional ways to iterate.


entrySet() method is the most efficient way to iterate through a Map and the For loop is more cleaner and readable than the Iterator.


Which collection classes provide random access of its elements?
-------------------------------------------------------------------
ArrayList and Vector implements the marker interface java.util.RandomAccess. Hence ArrayList, Vector and Stack provide random access of its elements.

How to avoid ConcurrentModificationException while iterating a collection?
---------------------------------------------------------------------------
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection. For example we can use CopyOnWriteArrayList
instead of ArrayList.

How can we create a synchronized collection from given collection?
---------------------------------------------------------------------
We can use Collections.synchronizedCollection()

How can ArrayList be synchronized without using Vector?
-------------------------------------------------------
List list = Collections.synchronizedList(new ArrayList());

How can we make HashMap synchronized?
----------------------------------------
Map map = Collections.synchronizedMap(new HashMap());

How to obtain Array from an ArrayList?
-------------------------------------------
ArrayList.toArray() method returns an array

How to convert a String array to ArrayList?
--------------------------------------------
using Arrays.asList() converts an array to a List and ArrayList provides a constructor that constructs an ArrayList from a Collection.
example :   
String[] stringArray = { "one", "two", "three" };
List<String> stringList = Arrays.asList(stringArray);
ArrayList<String> stringArrayList = new ArrayList<String>(stringList);

How to reverse a List?
-------------------------
Collections.reverse()

Why String, Integer and other wrapper classes are considered good keys?
----------------------------------------------------------------------
String, Integer and other wrapper classes are final or immutable classes and they have overridden equals() and hashCode() method as per the contract so they are
considered good keys.

Why there is no concrete implementation of Iterator interface?
-------------------------------------------------------------
A concrete implementation of an Iterator must decide between an ordered iteration or an unordered iteration which clearly leads to an iterator either for a List or
for a Set. Iterators of a List must be ordered because ordering is the heart of List whereas Set does not need ordering as an essential property and ordering a Set
makes a very special type of Set. Thus iterators are more specific functionality to specific collection types rather than applicable to all types of Collection.
Hence subclasses of Collection provide iterators that are specific to that collection type.

Why there is no method like Iterator.add() to add elements to the collection?
-----------------------------------------------------------------------------
Adding elements to the collection during the iteration is an unclear functionality and leads to an unordered iteration which is not desirable for ordered
collections

What are common algorithms implemented in Collections Framework?
---------------------------------------------------------------
The common algorithms implemented in Collections Framework are: sorting, searching, shuffling, swaping, min, max, rotate, addAll, replaceAll, etc.

What is Big-O notation?
--------------------------------------------
Big O notation is used to represent the complexity of an algorithm based on the input size. It is useful to choose the best algorithm to solve a problem.

What is the performance of various Java collection implementations/algorithms? What is Big ‘O’ notation for each of them?
----------------------------------------------------------------------------------------------------------------------------

ArrayList: The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding N elements requires O(N) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

LinkedList: Performance of get and remove methods is linear time [ Big O Notation is O(N) ] – Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]

HashSet: This class offers constant time performance for the basic operations like add, remove, contains and size assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance’s size that is the number of elements plus the “capacity” of the backing HashMap instance that is the number of buckets. Thus, it’s very important not to set the initial capacity too high or the load factor too low if iteration performance is important.

LinkedHashSet: Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.

A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.

TreeSet: This implementation provides guaranteed log(N) time cost for the basic operations like add, remove and contains.

Hashtable: An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

HashMap: This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the “capacity” of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

LinkedHashMap: Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

TreeMap: This implementation provides guaranteed log(N) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.
90. What is the difference between sorting performance of Arrays.sort() and Collections.sort()? Which one is faster? Which one to use and when?

Collections.sort() can sort only Lists and Arrays.sort() can sort only arrays. Internally Collections.sort() converts the List to an array and then it calls Arrays.sort() to sort it and then it converts the sorted array into a List whereas Arrays.sort() directly sorts the array.

Hence Arrays.sort() is faster than Collections.sort().

When we have a List we can use Collections.sort() and when we have an array we can use Arrays.sort().


What are best practices related to Java Collections Framework?
---------------------------------------------------------------
1. Choose the right type of collection based on the need.
2. Optimize the initial capacity to avoid rehashing or resizing.
3. Override equals() and hashCode() methods as per the contract.
4. Use polymorphic references to List, Set and Map instead of their concrete implementation.
5. Use Generics for type safety at compile time.
6. Use immutable classes as key in Map.
7. Use Collections utility methods for algorithms like sorting, searching, shuffling, swapping, reversing, synchronizing, read only collections, etc. rather than
writing own implementation.

What is load factor?
--------------------------
Load factor is the ratio of the number of elements of the hash table and the number of buckets.

What is Hashing?
-------------------
Hashing means using some function or algorithm to map object data to some representative integer value.

What is Hash Collision?
---------------------------
If the hash codes of two or more objects are same then it is known as hash collision.

What is Re-hashing?
-----------------------
Rebuilding the internal data structure of the hash table is known as rehashing. When the size of the hash table exceeds the threshold = capacity * load factor,
then all the elements are moved to a new bigger hash table. The hash code is calculated again to determine the bucket number so it is called rehashing.


How does put() and get() method of HashMap work?
-------------------------------------------------
The put() method with key and value is used to insert an element into the HashMap. The hash code of the key is calculated and the bucket is determined from the
hash code. If the bucket is empty then a new HashMap.Entry(hash, key, value, next) element is inserted into the bucket. If the bucket is not empty then all the
keys in the linked list is compared with the equals method to check if an element with the same key is already there or not. If the key is found then the value is
overwritten otherwise a new HashMap.Entry(hash, key, value, next) element is inserted at the end.

The get() method is used to get the value for a given key. The hash code of the key is calculated and the bucket is determined from the hash code. The linked list
present into the bucket is sequentially searched for the key. If the hash code matches and the key passes either == or equals() method then the value stored there
is returned.

 What will happen if two different HashMap key objects have same hashcode? How will you retrieve Value object if two Keys will have same hashcode?
-----------------------------------------------------------------------------------------------------------------------------------------------------
Two different HashMap key objects have same hashcode is known as hash collision. HashMap uses a doubly linked list for each bucket to resolve hash collision.
Both the keys will be stored into the same bucket as different nodes of the linked list.

The nodes of this linked list are of type HashMap.Entry(hash, key, value, next). The get() method is used to get the value for a given key. It will perform a
sequential search into the linked list present into the bucket. Since the hash code is same the key will be identified by any of the == or equals() method and
then the value stored into the HashMap.Entry will be returned.

J2EE PATTERNS

Presentation Tier:
---------------------
1. Interceptor Pattern : Pluggable filter intercept incoming request and outgoing response

2. Front Controller : Handles requests and manages content retrieval, security, view management,and navigation, delegating to a Dispatcher component to dispatch to a View.

3. View Helper : Generally suggested to view helper for formatting output also use business delegate to access business classes.

4. Composite View : Composite view design pattern is used when multiple subviews are directly embedded to make a single view or layout or template.

5. Dispatch View :  Dispatcher view is a combination of a controller and dispatcher with views and view helpers to handle client requests and prepare  a dynamic presentation as the response.

6. Service to Worker : This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part.


Business Tier :
----------------
1. Business Delegate : Primary target is to reduce coupling between presentation and business tier by provide a proxy to facade.  hiding the underlying implementation  details of the service .

2. Session Facade : Main focus of the facade is to split the total system into sub system by hiding the complexity. It helps to reduce network overhead and improve performance.

3. Transfer/Value Object : Used to exchange data across tiers.it also reduce the network overhead by minimizing the number of calls to get data from another tier.

4. Transfer/Value Object Assembler : Transfer Object Assembler combines multiple Transfer Objects from various business components and services, and returns it to the client.

5. Value List Handler : Value list handler is use to cache the results and allow client to search, traverse and select items from the results.

6. Service Locator  : The service locator design pattern is used when you to implement and encapsulate service and component lookup.

7. Composite Entity : Use Composite Entity to model, represent, and manage a set of interrelated persistent objects rather than representing them as individual

Integration Tier:
------------------
DAO : Encapsulate all access to persistence store.  DAO manages connection with data source to obtain and store data.

Service Activator : Service activator design pattern is use to receive asynchronous requests and invoke one or more business services.

Tuesday, November 5, 2013

Spring Related Question and Answer

1.  What is Spring?
----------------------
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application,but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

2. what are benefits of using spring?
----------------------------------------------
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

Container: Spring contains and manages the life cycle and configuration of application objects.

MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for  example) and scale up to global transactions (using JTA, for example).

Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

3. What are the different modules in Spring framework?
--------------------------------------------------------------------
1. Core Container Module : This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container

2.Application Context Module : The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for  internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

3.AOP module (Aspect Oriented Programming) : AOP module is used for developing aspects for Spring-enabled application

4.JDBC abstraction and DAO module

5.ORm integration module (Object/Relational)

6.Web module

7. MVC framework module

4. What is a BeanFactory?
---------------------------------
A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.

5. What is XMLBeanFactory?
--------------------------------------
BeanFactory has many implementations in Spring. But one of the most useful one is org. springframework. beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file.

6.What are important ApplicationContext implementations in spring framework?
--------------------------------------------------------------------------------------------------
ClassPathXmlApplicationContext – This context loads a context definition from an XML file located in theclass path, treating context definition files as class path resources.

FileSystemXmlApplicationContext – This context loads a context definition from an XML file in the filesystem.

XmlWebApplicationContext – This context loads the context definitions from an XML file contained within a web application.

7.  Explain Bean lifecycle in Spring framework?
-----------------------------------------------------------
1.The spring container finds the bean’s definition from the XML file and instantiates the bean.

2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.

3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing aninstance of itself.

5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.

7 .If an init-method is specified for the bean, it will be called.

8 Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

7. What is bean wiring?
------------------------------
Combining together beans within the Spring container is known as bean wiring or wiring.

8. What are singleton beans and how can you create prototype beans?
-----------------------------------------------------------------------------------
Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

9. What are the different types of bean injections?
---------------------------------------------------------------
There are two types of bean injections.

    By setter
    By constructor
   
10. What is Auto wiring?
------------------------------
we can wire the beans as you wish. But spring framework also does this work for us. It can auto wire the related beans together. All we have to do is
just set the autowire attribute of bean tag to an autowire type.

<bean id="bar" class="com.act.Foo" Autowire=”autowire type”/>

11. What are different types of Autowire types?
---------------------------------------------------------
There are four different types by which auto-wiring can be done.

        byName
        byType
        constructor
        autodetect

12. What are the different types of events related to Listeners?
--------------------------------------------------------------------------   
There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses oforg.springframework.context.
Application-Event. They are

    ContextClosedEvent – This is fired when the context is closed.
    ContextRefreshedEvent – This is fired when the context is initialized or refreshed.
    RequestHandledEvent – This is fired when the web context handles any request.   

13. What is an Aspect?
----------------------------
An aspect is the cross-cutting functionality that we are implementing. It is the aspect of our application we are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, we can create a logging aspect and apply it throughout the application using AOP.   

14. What is a Jointpoint?
------------------------------
A join point is a point in the execution of the application where an aspect can be plugged in.

15. What is an Advice?
---------------------------
Types of advice:

 Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

After throwing advice: Advice to be executed if a method exits by throwing an exception.

After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom  behaviour before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method   execution by returning its own return value or throwing an exception.


16. What is a Point cut?
----------------------------
A point cut  defines at what join points an advice should be applied.

17. What is a Target?
--------------------------
A target is the class that is being advised.

18. What is a Proxy?
-------------------------
A proxy is an object that is created after applying advice to a target object.

19. What is meant by Weaving?
------------------------------------
The process of applying aspects to a target object to create a new proxy object is called as Weaving.
The aspects are woven into the target object at the specified join points.

20 What are the different types of AutoProxying?
-----------------------------------------------------------
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying

Different points where weaving can be applied :
    Compile Time
    Classload Time
    Runtime
   
21. What are the benefits of IOC?
----------------------------------------
The main benefits of IOC or dependency injection are:

1. It minimizes the amount of code in your application.

2. It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.

3. Loose coupling is promoted with minimal effort and least intrusive mechanism.

4. IOC containers support eager instantiation and lazy loading of services.



22. What bean scopes does Spring support? Explain them.
--------------------------------------------------------
Singleton: Scopes a single bean definition to a single object instance per Spring IoC container. Default Scope.

prototype : Scopes a single bean definition to any number of object instances.

request : Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a  bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session : Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session : Scopes a single bean definition to the lifecycle of a global HTTP Session.Typically only valid when used in a portlet context. Only valid in  the context of a web-aware Spring ApplicationContext.

23 : How do you turn on annotation wiring?
---------------------------------------------------
A: Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

24 What is WebApplicationContext ?
-----------------------------------------------
A: The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with

25. Following are some of the advantages of Spring MVC over Struts MVC:
------------------------------------------------------------------------------------------------
Layered architecture that allows you to use what you need while leaving what you don’t need.
   
Spring's MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.

Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.

Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.

 In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.

 Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

 Struts force your Controllers to extend a Struts class but Spring doesn't, there are many convenience Controller implementations that you can choose to extend.

 In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.

 With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.

26.  What type of transaction Management Spring support?
--------------------------------------------------------------------------

Two type of transaction management is supported by spring

1. Programmatic transaction management :  used preferably when you have a small number of transactional operations

2. Declarative transaction management: In case of large number of transactional operations it is better to use declarative transaction management.


27. List new features for Spring 3.0
------------------------------------------
1: Spring Expression Language : Spring introduces an expression language which is similar to Unified EL

2. IoC enhancements/Java based bean meta-data : Annotation based configuration and Some core features from the JavaConfig project have been added

3. General-purpose type conversion system and field formatting system

4. Object to XML mapping functionality (OXM) moved from Spring Web Services project

5. Comprehensive REST support

6. @MVC additions

7. Declarative model validation

8. Early support for Java EE 6

9. Embedded database support
                

AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....