Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Sunday, 14 July 2013

Java serailization , transient , static concept in core java | core java interview questions

In core java interview questions, Serialization is one of the important topic in which we come across various questions like
What is Transient, Explain Serailization, What is serialversionUID, What is use of serialVersionUID, what is Serilization. (interface, class).
I have gone through various technical interview question websites and found that all answers are very short and dosent give idea of interrelated questions.

This tutorial will help beginners to understand everything related to serialization in one go.

Will first start with basic key points.
All objects in memory are exist only as long as java virtual machine running.
Serialization is process of writing objects to a stream and read from stream. Writing to a stream will make your object persistable. We can save object state on physical file system. and read it later whenever required and restore object state.
Using serialization we can maintain object state beyond java virtual machine lifetime.

Java provides mechnisam to persist the object.
Key points to use this mechanisam is. Your object should be serializable.
How can we make our object serializable? by implementing java.io.Serializble.
What about java library, system classes. Are all of them are serializable? No.
Most of the classes which makes sense to serialize are by default implementing Serializable. But some classes dosent make sense are not.
for E.g : String, Swing, AWT, Class implements Serializable.
Thread, ClassLoader, Socket, OutputStream ..dosent implement Serializable.

Key point to remember is why we need to implement Serializable explicitely? Because java.lang.Object dosent implement serializable. This facility is given to implementer.
What happens if your class is using one of the system class which is not serilizable..for e.g Thread, OutputStream?
Java provides transient keyword. (As mentioned earlier ..Making Thread serializable dosent make sense) so we can mark this member as transient and Serialization process will exclude this member from serialization.

What will be the value of transient variable when we read it back? it will be default value.. for string null.

Now we understood the concept of serialization, and what is use of transient.
Lets do simple example.
Create simple class.

package transientTest;

import java.io.Serializable;

public class TestClass implements Serializable{
private String fName;
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String lName;
private transient String password;
}

Test the class. Write to file and read from file.
package transientTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerialization {
public static void main(String... st) throws Exception{
ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
TestClass ts= new TestClass();
ts.setfName("Shashi");
ts.setlName("Jadhav");
ts.setPassword("pass");
obj.writeObject(ts);
obj.close();
ObjectInputStream objin= new ObjectInputStream(new FileInputStream(new File("Test.out")));
TestClass ts1=(TestClass)objin.readObject();
objin.close();
System.out.println("ts.getfName():"+ts1.getfName());
System.out.println("ts.getlName():"+ ts1.getlName());
// returns null: because TestClass.password is transient.
System.out.println("ts.getPassword():"+ ts1.getPassword());
TestClass1 ts12= (TestClass1)ts1.getTestcls();
System.out.println("test12:"+ts12.mname);
}
}
Looks very simple .. yes!
But we need to look at the few real time scenario.
Suppose you create the object, set the state and write to stream. In same execution you change the state of the object and try to write it again. What will be the behavior... ?
TestClass ts= new TestClass();
ts.setfName("Shashi");
ts.setlName("Jadhav");
ts.setPassword("pass");
obj.writeObject(ts);
ts.setlName("-----");
obj.writeObject(ts);
obj.close();

 In above code, you have changed the lName to ---- and again wrote the same object to stream..
Key point to remember.. ObjectOutputStream maintain a reference to an object written to it. That means if the state of the object is written and then written again. the new state will not be saved.
There are two ways to do it.
use reset().
close the stream and write it once again.
obj.reset();
obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
obj.writeObject(ts);
obj.close();

There are few other points you need to consider is about GC. once object is written to stream. make sure that object is availble for GC.

One more key point to remember ...or consider scenario..
You have a class which is persisted, and when you try to read it ... by that time class is modified (added new member..). What will happen?
By default if your class is changed after write.. you will not be able to read it.. because your class is modified. serialization will throw exception java.io.invalidClassException().
How serialization identifies that class is modified.. ?
Best answer is ..all persistent capable classes (Implements Serializable) are automatically given a unique identifier. if the identifier of the class is \not equal to the identifier of saved object.
How to resolve this issue... ? answer is serialVersionUID.
You assign the serialVersionUID to the class which will remain same before and after modification.

Eg: Create a class using serialVersionUID.
package transientTest.readwritemodify;

import java.io.Serializable;

public class TestClass implements Serializable{
static final long serialVersionUID= 1l;

private String name;
private String lname;
public String getLname() {
return lname;
}

public void setLname(String lname) {
this.lname = lname;
}

public String getName() {
return name;
}

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

}

Now.. even if your class is modified but the serialversionUID remains the same.. you will be able to read and write. only additioanl state you have added after modification will be set to null

How can you get serialVersionUID runtime?
use :
ObjectStreamClass.getSerialVersionUID(o.getClass());
serialver is one more utility can be used to get the class version.

What if a super class/interface implements a serializable and you dont want your implementing/extending class to provide this facility.
you can override 2 methods and throw exception.

private void writeObject(ObjectOutputStream out)throws IOException{
throw new NotSerializableException("");
}

private void readObject(ObjectInputStream in) throws IOException{
throw new NotSerializableException("");
}

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...