<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Interview Questions &#187; Java Serialization</title>
	<atom:link href="http://www.bestjavainterviewquestions.com/category/java-important-notes/java-serialization/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bestjavainterviewquestions.com</link>
	<description>Java Interview Questions &#124; Core Java Interview Questions &#124; Advanced Java Interview Questions &#124; EJB Interview Questions &#124; J2EE Interview Questions &#124; Hibernate Interview Questions</description>
	<lastBuildDate>Fri, 03 Feb 2012 10:23:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to Make a Class Serializable</title>
		<link>http://www.bestjavainterviewquestions.com/how-to-make-a-class-serializable/</link>
		<comments>http://www.bestjavainterviewquestions.com/how-to-make-a-class-serializable/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 11:59:59 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[Java Serialization]]></category>
		<category><![CDATA[deserialization]]></category>
		<category><![CDATA[marker interface]]></category>
		<category><![CDATA[serializable]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=613</guid>
		<description><![CDATA[So far, we&#8217;ve focused on the mechanics of serializing an object. We&#8217;ve assumed we have a serializable object and discussed, from the point of view of client code, how to serialize it. The next step is discussing how to make a class serializable. Serialization is also called as Marker Interface There are four basic things [...]]]></description>
			<content:encoded><![CDATA[<p>So far, we&#8217;ve focused on the mechanics of serializing an object. We&#8217;ve assumed we have a serializable object and discussed, from the point of view of client code, how to serialize it. The next step is discussing how to make a class serializable.</p>
<p>Serialization is also called as Marker Interface</p>
<p><strong><em>There are four basic things you must do when you are making a class serializable. They are:</em></strong></p>
<p>1. Implement the Serializable interface.</p>
<p>2. Make sure that instance-level, locally defined state is serialized properly.</p>
<p>3. Make sure that superclass state is serialized properly.</p>
<p>4. Override equals( ) and hashCode( ).</p>
<p>Let&#8217;s look at each of these steps in more detail.<br />
Implement the Serializable Interface</p>
<p>This is by far the easiest of the steps. The Serializable interface is an empty interface; it declares no methods at all. So implementing it amounts to adding &#8220;implements Serializable&#8221; to your class declaration.</p>
<p>Reasonable people may wonder about the utility of an empty interface. Rather than define an empty interface, and require class definitions to implement it, why not just simply make every object serializable? The main reason not to do this is that there are some classes that don&#8217;t have an obvious serialization. Consider, for example, an instance of File. An instance of File represents a file. Suppose, for example, it was created using the following line of code:</p>
<p>File file = new File(&#8220;c:\\New Floder\\Temp&#8221;);</p>
<p>It&#8217;s not at all clear what should be written out when this is serialized. The problem is that the file itself has a different lifecyle than the serialized data. The file might be edited, or deleted entirely, while the serialized information remains unchanged. Or the serialized information might be used to restart the application on another machine, where &#8220;C:\\New Floder\\Temp&#8221; is the name of an entirely different file.</p>
<p>Another example is provided by the Thread[4] class. A thread represents a flow of execution within a particular JVM. You would not only have to store the stack, and all the local variables, but also all the related locks and threads, and restart all the threads properly when the instance is deserialized.</p>
<p>TIP:   Things get worse when you consider platform dependencies. In general, any class that involves native code is not really a good candidate for serialization.</p>
<p>Make Sure That Instance-Level, Locally Defined State Is Serialized Properly</p>
<p>Class definitions contain variable declarations. The instance-level, locally defined variables (e.g., the nonstatic variables) are the ones that contain the state of a particular instance. For example, in our Money class, we declared one such field:</p>
<p>public class Money extends ValueObject {<br />
private int _cents;<br />
&#8230;.<br />
}</p>
<p>The serialization mechanism has a nice default behavior&#8211;if all the instance-level, locally defined variables have values that are either serializable objects or primitive datatypes, then the serialization mechanism will work without any further effort on our part. For example, our implementations of Account, such as Account_Impl, would present no problems for the default serialization mechanism:</p>
<p>public class Account_Impl extends UnicastRemoteObject implements Account {<br />
private Money _balance;<br />
&#8230;<br />
}</p>
<p>While _balance doesn&#8217;t have a primitive type, it does refer to an instance of Money, which is a serializable class.</p>
<p>If, however, some of the fields don&#8217;t have primitive types, and don&#8217;t refer to serializable classes, more work may be necessary. Consider, for example, the implementation of ArrayList from the java.util package. An ArrayList really has only two pieces of state:</p>
<p>public class ArrayList extends AbstractList implements List, Cloneable, java.io.<br />
Serializable {<br />
private Object elementData[];<br />
private int size;<br />
&#8230;<br />
}</p>
<p>But hidden in here is a huge problem: ArrayList is a generic container class whose state is stored as an array of objects. While arrays are first-class objects in Java, they aren&#8217;t serializable objects. This means that ArrayList can&#8217;t just implement the Serializable interface. It has to provide extra information to help the serialization mechanism handle its nonserializable fields. There are three basic solutions to this problem:<br />
<em><br />
<strong>* Fields can be declared to be transient.</strong></em></p>
<p><strong><em>* The writeObject( )/readObject( ) methods can be implemented.</em></strong></p>
<p><strong><em>* serialPersistentFields can be declared. </em></strong></p>
<p>&nbsp;</p>
<p><em><strong>You can find more information on serialization</strong></em> at <a title="Using Serialization" href="http://www.bestjavainterviewquestions.com/using-serialization/" target="_blank">1</a> and <a title="Brief information about serialization" href="http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/" target="_blank">2</a></p>
<h2  class="related_post_title">Related Post</h2><ul class="related_post"><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/" title="Explain Briefly about Serialization">Explain Briefly about Serialization</a> (0)</li><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/using-serialization/" title="Using Serialization ">Using Serialization </a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/how-to-make-a-class-serializable/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Serialization</title>
		<link>http://www.bestjavainterviewquestions.com/using-serialization/</link>
		<comments>http://www.bestjavainterviewquestions.com/using-serialization/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 11:53:11 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[Java Serialization]]></category>
		<category><![CDATA[deserialization]]></category>
		<category><![CDATA[examples of deserialization]]></category>
		<category><![CDATA[examples of serialization]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[uses of serialization]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=610</guid>
		<description><![CDATA[Serialization is a mechanism built into the core Java libraries for writing a graph of objects into a stream of data. This stream of data can then be programmatically manipulated, and a deep copy of the objects can be made by reversing the process. This reversal is often called deserialization. Note: When serializing an object [...]]]></description>
			<content:encoded><![CDATA[<p>Serialization is a mechanism built into the core Java libraries for writing a graph of objects into a stream of data. This stream of data can then be programmatically manipulated, and a deep copy of the objects can be made by reversing the process. This reversal is often called deserialization.</p>
<p><em><strong>Note: </strong>When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.</em></p>
<p><strong><em>import java.io.*;</em></strong></p>
<p><strong><em>public class SerializeDemo<br />
{</em></strong></p>
<p><strong><em>public static void main(String [] args)<br />
{</em></strong></p>
<p><strong><em>Employee e = new Employee();<br />
e.name = &#8220;Ramakrishna&#8221;;<br />
e.address = &#8220;Hyderabad&#8221;;<br />
e.SSN = 11122333;<br />
e.number = 200113;</em></strong></p>
<p><strong><em>try<br />
{</em></strong></p>
<p><strong><em>FileOutputStream fileOut =<br />
new FileOutputStream(&#8220;employee.ser&#8221;);<br />
ObjectOutputStream out =<br />
new ObjectOutputStream(fileOut);<br />
out.writeObject(e);<br />
out.close();<br />
fileOut.close();</em></strong></p>
<p><strong><em>}catch(IOException i)<br />
{<br />
i.printStackTrace();<br />
}<br />
}<br />
}</em></strong></p>
<p><em>The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:</em></p>
<p><strong><em>import java.io.*;</em></strong></p>
<p><strong><em>public class DeserializeDemo<br />
{</em></strong></p>
<p><strong><em>public static void main(String [] args)<br />
{</em></strong></p>
<p><strong><em>Employee e = null;</em></strong></p>
<p><strong><em>try<br />
{<br />
FileInputStream fileIn =<br />
new FileInputStream(&#8220;employee.ser&#8221;);<br />
ObjectInputStream in = new ObjectInputStream(fileIn);<br />
e = (Employee) in.readObject();<br />
in.close();<br />
fileIn.close();<br />
}catch(IOException i)<br />
{<br />
i.printStackTrace();<br />
return;</em></strong></p>
<p><strong><em>}catch(ClassNotFoundException c)<br />
{<br />
System.out.println(.Employee class not found.);<br />
c.printStackTrace();<br />
return;<br />
}</em></strong></p>
<p><strong><em>System.out.println(&#8220;Deserialized Employee&#8230;&#8221;);<br />
System.out.println(&#8220;Name: &#8221; + e.name);<br />
System.out.println(&#8220;Address: &#8221; + e.address);<br />
System.out.println(&#8220;SSN: &#8221; + e.SSN);<br />
System.out.println(&#8220;Number: &#8221; + e.number);<br />
}<br />
}</em></strong></p>
<p><em>This would produce following result:</em></p>
<p><em>Deserialized Employee&#8230;<br />
Name: Ramakrishna<br />
Address:Hyderabad<br />
SSN: 0<br />
Number:200113</em></p>
<p><strong><em><br />
</em></strong></p>
<p>In particular, there are three main uses of serialization:</p>
<p>As a persistence mechanism<br />
If the stream being used is FileOutputStream, then the data will automatically be written to a file.</p>
<p>As a copy mechanism<br />
If the stream being used is ByteArrayOutputStream, then the data will be written to a byte array in memory. This byte array can then be used to create duplicates of the original objects.</p>
<p>As a communication mechanism<br />
If the stream being used comes from a socket, then the data will automatically be sent over the wire to the receiving socket, at which point another program will decide what to do.</p>
<p>The important thing to note is that the use of serialization is independent of the serialization algorithm itself. If we have a serializable class, we can save it to a file or make a copy of it simply by changing the way we use the output of the serialization mechanism.</p>
<p>As you might expect, serialization is implemented using a pair of streams. Even though the code that underlies serialization is quite complex, the way you invoke it is designed to make serialization as transparent as possible to Java developers. To serialize an object, create an instance of ObjectOutputStream and call the writeObject( ) method; to read in a serialized object, create an instance of ObjectInputStream and call the readObject( ) object.</p>
<p><strong>TIP: </strong> <em>There are two versions of the serialization protocol currently defined: PROTOCOL_VERSION_1 and PROTOCOL_VERSION_2. If you send serialized data to a 1.1 (or earlier) JVM, you should probably use PROTOCOL_VERSION_1. The most common case of this involves applets. Most applets run in browsers over which the developer has no control. This means, in particular, that the JVM running the applet could be anything, from Java 1.0.2 through the latest JVM. Most servers, on the other hand, are written using JDK1.2.2 or later.[3] If you pass serialized objects between an applet and a server, you should specify the serialization protocol. </em></p>
<h2  class="related_post_title">Related Post</h2><ul class="related_post"><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/how-to-make-a-class-serializable/" title="How to Make a Class Serializable">How to Make a Class Serializable</a> (1)</li><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/" title="Explain Briefly about Serialization">Explain Briefly about Serialization</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/using-serialization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Explain Briefly about Serialization</title>
		<link>http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/</link>
		<comments>http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 11:49:08 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[Java Important Notes]]></category>
		<category><![CDATA[Java Serialization]]></category>
		<category><![CDATA[define serialization]]></category>
		<category><![CDATA[deserialization]]></category>
		<category><![CDATA[explain serialization]]></category>
		<category><![CDATA[marker interface]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=608</guid>
		<description><![CDATA[Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, [...]]]></description>
			<content:encoded><![CDATA[<p>Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by <a class="wp-caption" title="Frequently Asked Questions of RMI" href="http://www.bestjavainterviewquestions.com/java-rmi-interview-questions/" target="_blank">RMI </a>to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, I referred to this process several times but delayed a detailed discussion until now. In this chapter, we drill down on the serialization mechanism; by the end of it, you will understand exactly how serialization works and how to use it efficiently within your applications.</p>
<p>What does it mean for the client to pass an instance of Money to the server? At a minimum, it means that the server is able to call public methods on the instance of Money. One way to do this would be to implicitly make Money into a server as well.[1] For example, imagine that the client sends the following two pieces of information whenever it passes an instance as an argument:</p>
<ul>
<li><em> <strong>The type of the instance; in this case, Money.</strong></em></li>
<li><strong><em> A unique identifier for the object (i.e., a logical reference). For example, the address of the instance in memory.</em></strong></li>
</ul>
<p>The RMI runtime layer in the server can use this information to construct a stub for the instance of Money, so that whenever the Account server calls a method on what it thinks of as the instance of Money, the method call is relayed over the wire</p>
<p>Attempting to do things this way has three significant drawbacks:</p>
<ul>
<li><em> <strong>You can&#8217;t access fields on the objects that have been passed as arguments.</strong></em></li>
</ul>
<p>Stubs work by implementing an interface. They implement the methods in the interface by simply relaying the method invocation across the network. That is, the stub methods take all their arguments and simply marshall them for transport across the wire. Accessing a public field is really just dereferencing a pointer&#8211;there is no method invocation and hence, there isn&#8217;t a method call to forward over the wire.</p>
<ul>
<li><em> <strong>It can result in unacceptable performance due to network latency.</strong></em></li>
</ul>
<p>Even in our simple case, the instance of Account is going to need to call getCents( ) on the instance of Money. This means that a simple call to makeDeposit( ) really involves at least two distinct networked method calls: makeDeposit( ) from the client and getCents( ) from the server.</p>
<ul>
<li><em> <strong>It makes the application much more vulnerable to partial failure.</strong></em></li>
</ul>
<p>Let&#8217;s say that the server is busy and doesn&#8217;t get around to handling the request for 30 seconds. If the client crashes in the interim, or if the network goes down, the server cannot process the request at all. Until all data has been requested and sent, the application is particularly vulnerable to partial failures.</p>
<p>This last point is an interesting one. Any time you have an application that requires a long-lasting and durable connection between client and server, you build in a point of failure. The longer the connection needs to last, or the higher the communication bandwidth the connection requires, the more likely the application is to occasionally break down.<br />
TIP: The original design of the Web, with its stateless connections, serves as a good example of a distributed application that can tolerate almost any transient network failure. These three reasons imply that what is really needed is a way to copy objects and send them over the wire. That is, instead of turning arguments into implicit servers, arguments need to be completely copied so that no further network calls are needed to complete the remote method invocation. Put another way, we want the result of makeWithdrawal( ) to involve creating a copy of the instance of Money on the server side. The runtime structure should resemble</p>
<p>The desire to avoid unnecessary network dependencies has two significant consequences:</p>
<ul>
<li><strong><em>Once an object is duplicated, the two objects are completely independent of each other.</em></strong></li>
</ul>
<p>Any attempt to keep the copy and the original in sync would involve propagating changes over the network, entirely defeating the reason for making the copy in the first place.</p>
<ul>
<li><strong><em>The copying mechanism must create deep copies.</em></strong></li>
</ul>
<p>If the instance of Money references another instance, then copies must be made of both instances. Otherwise, when a method is called on the second object, the call must be relayed across the wire. Moreover, all the copies must be made immediately&#8211;we can&#8217;t wait until the second object is accessed to make the copy because the original might change in the meantime.</p>
<p>These two consequences have a very important third consequence:</p>
<ul>
<li><strong><em>If an object is sent twice, in separate method calls, two copies of the object will be created.</em></strong></li>
</ul>
<p>In addition to arguments to method calls, this holds for objects that are referenced by the arguments. If you pass object A, which has a reference to object C, and in another call you pass object B, which also has a reference to C, you will end up with two distinct copies of C on the receiving side.</p>
<h2  class="related_post_title">Related Post</h2><ul class="related_post"><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/how-to-make-a-class-serializable/" title="How to Make a Class Serializable">How to Make a Class Serializable</a> (1)</li><li>July 21, 2010 -- <a href="http://www.bestjavainterviewquestions.com/using-serialization/" title="Using Serialization ">Using Serialization </a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/explain-briefly-about-serialization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

