When to use ConcurrentHashMap in Java | Key summary of ConcurrentHashMap | Java collection interview Question

ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable. Performance of CHM drops, because you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads. As javadoc states, CHM is also a good replacement of Hashtable and should be used whenever possible, keeping in mind, that CHM provides slightly weeker form of synchronization than Hashtable.


Summary
Now we know What is ConcurrentHashMap in Java and when to use ConcurrentHashMap, it’s time to know and revise some important points about CHM in Java.

1. ConcurrentHashMap allows concurrent read and thread-safe update operation.

2. During update operation, ConcurrentHashMap only lock a portion of Map instead of whole Map.

3. Concurrent update is achieved by internally dividing Map into small portion which is defined by concurrency level.

4. Choose concurrency level carefully as a significant higher number can be waste of time and space and lower number may introduce thread contention in case writers overnumber concurrency level.

5. All operations of ConcurrentHashMap are thread-safe.

6. Since ConcurrentHashMap implementation doesn't lock whole Map, there is chance of read overlapping with update operations like put() and remove(). In that case result returned by get() method will reflect most recently completed operation from there start.

7. Iterator returned by ConcurrentHashMap is weekly consistent, fail safe and never throw ConcurrentModificationException. In Java.

8. ConcurrentHashMap doesn't allow null as key or value.

9. You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn't lock whole Map.

10. During putAll() and clear() operations, concurrent read may only reflect insertion or deletion of some entries.

That’s all on What is ConcurrentHashMap in Java and when to use it. We have also seen little bit about internal working of ConcurrentHashMap and how it achieves it’s thread-safety and better performance over Hashtable and synchronized Map. Use ConcurrentHashMap in Java program, when there will be more reader than writers and it’s a good choice for creating cache in Java as well.

Diffrence between Spring MVC and Struts MVC | MindMill Software Ltd interview question 2013

Date of interview 21 Feb 2013

In technical round they asked to tell difference between Spring MVC and Struts MVC

Spring is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise services to Plain Old Java Objects (POJOs). Spring uses dependency injection to achieve simplification and increase testability.
1. Spring provides a very clean division between controllers, JavaBean models, and views.
2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.
3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.
4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism – for example, your own templating language – you can easily implement the Spring View interface to integrate it.
5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.
6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.
8. No ActionForms. Bind directly to domain objects
9. More testable code (validation has no dependency on Servlet API)
10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.
11. Spring has a well defined interface to business layer
12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)
 

Error Cannot find ActionMappings or ActionFormBeans collection , Cannot retrieve mapping for action in Struts 1.2.

Cannot find ActionMappings or ActionFormBeans collection  , when he access the login.jsp of  the application deployed in WebSphere Application Server (WAS)  running on the Linux server. The application was developed using the framework  struts 1.2 and the application works fine with ide WSAD. The above error is thrown when the application server executes the  following line

<html:form name="loginForm" type="Sales.login.LoginForm" method="post" scope="request" action="/login.do" onsubmit="return submitForm()" >
 

The above error may occur due to various reasons.

Some of the situations  where the error may be thrown are as follows

Situation 1 :  When the Request Processor  searches for  the mapping of  this request, if  it is not able to  find the mappings that  are defined in the struts-config.xml , the following errors may be thrown depending upon the situation.

a)  If  the server is able to load the struts-config.xml , but the   mapping  is not available in the struts-config.xml . for eg.  if  the JSP has  <html:form action="/login" method="post" type="LoginAction">
                         then your struts-config.xml should have mapping for action parameter i.e. "/login"  something like

<action-mappings>
    <action path="/login"        type="LoginAction"    name="loginForm"          scope="request"       validate="false"   input="/login.jsp" >
     </action>
</action-mappings>


But if the mapping is not present in the   struts-config.xml , then you may get the error    [Cannot retrieve mapping for action /login1]: javax.servlet.jsp.JspException: Cannot retrieve mapping for action /login

b) But the above mapping is present in the struts-config.xml  , but you are getting the error  Cannot find ActionMappings or ActionFormBeans collection   ,  That means the sever is not able to load the struts-config.xml fle.

 To solve , the above problem ,  Please ensure , the path & file name of struts-config.xml file mentioned in the web.xml file  is correct and case sensitive.

  In our  case , the problem was very silly and the problem got solved when i  add a slash (/) infront of WEB-INF ...

The belows lines are part of the web.xml and the param-value  to be passed to  ActionServlet is wrongly mentioned

<servlet>
   <servlet-name>action</servlet-name>
   <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   <init-param>
    <param-name>config</param-name>
    <param-value>WEB-INF/struts-config.xml</param-value>   OR   <param-value>/web-inf/struts-config.xml</param-value>    // Wrong
   </init-param>
 

In the above lines  , changing  the line   <param-value>WEB-INF/struts-config.xml</param-value> OR  <param-value>web-inf/struts-config.xml</param-value>  to

<param-value>/WEB-INF/struts-config.xml</param-value>  , will solve the problem


Situation 2 :   If   the sever is able to load the struts-config.xml fle and also the  mapping is present in the struts-config.xml , then the Request Processor does  process  any ActionForm bean related to this request. (i.e. finding , loading  the ActionFormBeans collection, ..etc ) .

             Various classes such as org.apache.struts.action.ActionFormBeans ,  org.apache.commons.collections.FastHashMap   are involved for the above process.  And the following jars are  involved
                  struts.ear
                  commons-collections.jar
                   commons-beanutils.jar

  ....
  .....
            So  If you miss the jar files such as    commons-collections.jar  , commons-beanutils.jar in the class path , then the request processor may not find the ActionFormBeans collection , and the error Cannot find ActionMappings or ActionFormBeans collection  is thrown

Generics in Java | How to write parametrized class and method in Java | java Generics interview Question answer

Before to going start how write  parametrized class and method in Java . i would like to give some important fact about generic

1. java generic has introduced with JDK 1.5 along with Autoboxing, varargs, ,Enum
2. Generics  provide compile-time type safety that allows programmers to catch invalid types at compile time.
3. Not only can Java generics be used in fields and methods, it can also be used in class definitions to produce parameterized classes.


How to write  parametrized class

1. A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

2. As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas.

public class Member<T> {
 private T id;
 public Member(T id) {
   this.id = id;
 }
 public T getId() {
   return id;
 }
 public void setId(T id) {
   this.id = id;
 }
 public static void main(String[] args) {
   Member<String> mString = new Member<String>("id1");
   mString.setId("id2");
   System.out.printf("id after setting id: %s%n", mString.getId());
   //output:  id after setting id: id2
 
   Member<Integer> mInteger = new Member<Integer>(1);
   mInteger.setId(2);
   System.out.printf("id after setting id: %d%n", mInteger.getId());
   //output:  id after setting id: 2
 }


How to write parametrized method

 1.All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).

    2. Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type        name.

   3.  The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type        arguments.

   4.  A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types not primitive types (like int, double and char).

public class GenericMethodTest
{
   // generic method printArray                        
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements             
         for ( E element : inputArray ){       
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    }
}

Java Clone() concept | how clone work in java | java clone interivew question answer

First of all Java clone() method has given in Object class with below
protected Object clone() throws CloneNotSupportedException

with above definition some time in interview question you will found like
  • Why clone() method has given in Object class
  • What is the reason behind to make clone() method protected
  • What meaning of CloneNotSupportExeption
  • What is Shallow cloning and deep cloning

Definition
Clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Use of Cloneable interface
 
We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Java clone() concept


1. Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.  The assignment of one reference to another merely creates another reference to the same object.
2.  When you don't want to modify the method caller's (or original) object.
 Different analysis on same set of data in an Object. Rather than fetching the data again and again, populate object once and clone it for a new analysis.
 Games - walls, doors, cars graphics - clone the object, change the params.
3.For any class to able to be cloned .clone() - it MUST implement java.lang.Cloneable interface. Otherwise is .clone is used, it throws java.lang.CloneNotSupportedException at runtime.
  It is a marker interface - which simply tells JVM that the Object.clone() method can be called on the objects of this or sub classes.
4. Shallow Copy - see clone() method in below code
 This is a result of the default cloning functionality provided by the Object.clone()
 When this is used, it copies the primitives and the references. Only references are copied to new cloned Object. Actual referenced object remains as it. That means, the member references in original and cloned object - point to same object.
 
5.  Deep Copy - see deepClone() method in below code
 Copy the actual member objects along with primitives and member references.
 We need to override the clone() method in order to achieve it. But need to make sure that member Objects that we are trying to copy, should also implement Cloneable, only then then can be cloned.
 
 
public class Clones {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("AAA", 123, 100, 200);
System.out.println("Original");
System.out.println(p1.salary.basic);
Person p2 = (Person) p1.deepClone();
//p2.name = "BBB";
//p2.salary.basic = 2222;
System.out.println(p1.equals(p2));
System.out.println("Clone");
System.out.println(p2.salary.basic);
System.out.println("Original");
System.out.println(p1.salary.basic);
}
}
// cloneable class implements Cloneable
class Person implements Cloneable {
public String name = null;
public int id = 0;
public Salary salary = null;
public Person(String name, int id, int basicSal, int bonusSal) {
this.name = name;
this.id = id;
// using Object type member to test for cloning
Salary sal = new Salary();
sal.basic = basicSal;
sal.bonus = bonusSal;
this.salary = sal;
}
// shallow copying
protected Object clone() throws CloneNotSupportedException {
// This is default cloning provided by the Object.clone()
return super.clone();
}
// deep copying
protected Object deepClone() throws CloneNotSupportedException {
// The clone() method produces an Object, which must be recast to the proper type
Person p = (Person) super.clone();
// In deep cloning, we also clone the member objects, but for this to work - //member objects should be Cloneable
p.salary = (Salary) p.salary.clone();
return p;
}
}
// member object of Person class as Cloneable. If it was not, then deep cloning //would not have been possible
class Salary implements Cloneable {
public int basic = 0;
public int bonus = 0;
public int getSalary() {
return basic + bonus;
}
// implementing clone()
protected Salary clone() throws CloneNotSupportedException {
Salary s = (Salary) super.clone();
return s;
}
}
// Cloneables with final fields - not meant go together. No error, but when try //to change, it cribs.
// The only solution is to remove the final modifier from the field, giving up //the benefits the modifier conferred.

Java interview question related Session listner, web services in MNC software company

Below Few Java interview question asked at MNC software company

1. How can you count active sessions by using listeners in JAVA.

we can do it by using HttpSessionListener for that you can create a session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.
 
Code  example,
 we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.


package com.xyzws.web.utils;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}


To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into our /WEB-INF/web.xml file:

   <!-- Listeners -->  <listener>    <listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>  </listener>

For show in JSP
 the following JSP code shows the total active session:
 <%@ page import="com.xyzws.utils.MySessionCounter"%><html>...  Active Sessions : <%= MySessionCounter.getActiveSessions() %>...</html>

2) what is XML schema and it tags??
 
Definition
An XML Schema defines and describes certain types of XML data by using the XML Schema definition language (XSD). XML Schema elements (elements, attributes, types, and groups) are used to define the valid structure, valid data content, and relationships of certain types of XML data. XML Schemas can also provide default values for attributes, and elements.


XML Schema has contains below :

  • The first statement, <?xml version="1.0" encoding="utf-8"?>, specifies the version of XML in use.

  • The second statement consists of several parts:

The xs:schema declaration indicates that this is a schema and that the xs: prefix will be used before schema items.

The xmlns:xs="http://www.w3.org/2001/XMLSchema" declaration indicates that all tags in this schema should be interpreted according to the default namespace of the World Wide Web Consortium (W3C), which was created in 2001.

The targetnamespace declaration names this schema as XMLSchema1.xsd and indicates its default location, which will be in a default URI (universal resource identifier) on your development server called tempuri.org.

When you create a schema with the XML Designer, the version and namespace statements are automatically added for you. You might modify the contents of these two declarations in some cases. For example, if you want to use a tag prefix other than "XS," you would need to define the default namespace for that tag in addition to the XS tag prefix.

A complex type called "addressType" is defined that will contain five elements of various data types. Note that each of the elements it contains is a simple, named type.


Example

How to write XML schema of below requirments
The final element in the purchaseOrder, Item, contains a facet called maxOccurs. Facets set limits on the type of content a simple type can contain. maxOccurs is used to constrain how many times an element can occur in the documents created from this schema. By default, maxOccurs is equal to one. In this case, setting it to unbounded indicates that the Item element can reoccur as many times as needed.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="addressType">
   <xs:sequence>
      <xs:element name="street1" type="xs:string"/>
      <xs:element name="street2" type="xs:string"/>
      <xs:element name="city" type="xs:string"/>
      <xs:element name="state" type="xs:string"/>
      <xs:element name="zip" type="xs:integer"/>
   </xs:sequence>
</xs:complexType>

<xs:element name="purchaseOrder">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="shipTo" type="addressType" />
            <xs:element name="billTo" type="addressType" />
            <xs:element name="shipDate" type="xs:date" />
            <xs:element name="item" maxOccurs="unbounded"/>
         </xs:sequence>
      </xs:complexType>
   </xs:element>
</xs:schema>

Java Serialization concept | Most asked Serialization Interview Questions and Answers in MNC software company

Java Serialization is very important topic in interview . in every java interview question in MNC software company i face java serialization topic . below list of question you should remember well before going to interview


1) What is the difference between Serializable and Externalizable interface in Java?
This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.io  package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that useJava Serialization mechanism to serialize this object.

3) What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . serialVersionUID is used for version control of object. you can specify serialVersionUIDin your class file also.  Consequence of not specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.



4) While serializing you want some of the members not to serialize? How do you achieve it?
this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during java serialization process.

5) What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class.


6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?

Java serialization process  only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process . once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializableinterface , there constructor will be executed.

7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since onlyJava Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.

8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interviewprogresses.

9) Which methods are used during Serialization and DeSerialization process in java?
This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type.

10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

11)What are the ways to speed up Object Serialization? How to improve Serialization performance?
The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.

  •     Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
  •     Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
  •     Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.

12) What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:

    Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database.
    Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations.
    JSON Data Transfer - is recently popular data transfer format. A lot of web services are being developed in JSON due to its small footprint and inherent integration with web browser due to JavaScript format.
    Use Externalizable interface and implement the readObject and writeObject methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.


13)What changes are compatible and incompatible to the mechanism of java Serialization?
This is one of a difficult tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:

  •     Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled.
  •     The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream.
  •     Changing a transient field to a non-transient field is compatible change since it is similar to adding a field.
  •     Changing a static field to a non-static field is compatible change since it is also similar to adding a field.

Some Simple Examples of incompatible changes are:

  •     Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream.
  •     Deleting a existing Serializable fields will cause a problem.
  •     Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field.
  •     Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field.
  •     Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field.
  •     Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream.