Serialization in Java: Understanding Object Serialization and Its Uses, Slides of Computer Engineering and Programming

An overview of serialization in java, explaining what it is, how it works, and its various applications. Topics covered include object serialization, the use of objectinputstream and objectoutputstream, and the serialization api. The document also includes examples of writing and reading serialized objects, as well as customizing serialization for specific classes.

Typology: Slides

2011/2012

Uploaded on 07/11/2012

dhananad
dhananad 🇮🇳

4

(4)

39 documents

1 / 32

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download Serialization in Java: Understanding Object Serialization and Its Uses and more Slides Computer Engineering and Programming in PDF only on Docsity!

What is Serialization

 The process of storing or retrieving information

through a standard protocol

Use of Object Serialization

 RMI (Remote Method Invocation)

 communication between objects via sockets

 Lightweight persistence

 archival of an object for use in a later invocation of the

program

 Object lifetime :

  created by the new operator  … exists …  † destroyed by the Java VM’s garbage collector when the program no longer holds a reference to the object

Serialization API

5

CLASS DESCRIPTION

ObjectOutputStream Use this output stream to convert objects from the

in-memory form to serial form. This stream
implements the ObjectOutput interface.

ObjectInputStream Use this input stream to restore objects from the

serial form. This stream implements the
ObjectInput interface.

Serializable

Implement this interface to indicate that the class
can be converted to a serial form and to define
methods that can be overridden to control the
encoding of the class.

Serialization API (cont.)

7

Constructor/Method Description

ObjectInputStream(InputStream) Creates an ObjectInputStream that reads from the specified InputStream. readObject() Reads an object from the input stream; is the opposite of writeObject(). available() Returns the number of bytes that can be read without blocking. close() Closes the input stream. readInt() Reads a 32-bit int from the stream.

defaultReadObject()

Reads the nonstatic and nontransient fields of the current class from the stream, ensuring the standard encoding format. You can call this method only from the readObject() method of the class being decoded.

For more details consult the Java API.

Serialization API (cont.)

8

 The Serializable interface defines no methods but is an indicator that the
class is compatible with serialization and may have private readObject()
and writeObject() methods to control serialization.
 Only the data in the objects and the declarations of the classes are
encoded in the byte stream; the Java VM bytecodes that implement the
methods of the classes are not stored when an object is serialized.
 When the object is retrieved from the stream, the class declaration is
read and the normal class-loading mechanisms are used to load the
code.
 If a matching class is not found, readObject() throws
ClassNotFoundException.

Serializing Objects-reading

10

 Reading objects from a stream :

 ObjectInputStream must be constructed on another stream.

(Here, the objects were archived in a file, so the code constructs an ObjectInputStream on a FileInputStream.)

 Use ObjectInputStream's readObject method to read the String and the Date objects from the file.

 The objects must be read from the stream in the same order in which they were written. Note that the return value from readObject is an object that is cast to and assigned to a specific type.

FileInputStream in = new FileInputStream("theTime"); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Date)s.readObject();

Example

Object object = new javax.swing.JButton("push me") ;
try { // Serialize to a file
ObjectOutput out = new ObjectOutputStream(new
FileOutputStream( "filename.ser" ));
out.writeObject(object);
out.close(); // Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close(); // Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) { }

Serializing Objects (cont.)

13

/** pstruct is an object containing fields of different types, e.g. String, double, etc.*/

obj_outs.writeObject(pstruct.product_id);

obj_outs.writeObject(pstruct.product_name);

obj_outs.writeObject(pstruct.product_description);

obj_outs.writeObject(new Double(pstruct.price));

obj_outs.writeObject(pstruct.currency);

obj_outs.writeObject(new Boolean(pstruct.soft_good_p));

obj_outs.writeObject(new Boolean(pstruct.for_sale_p));

obj_outs.writeObject(pstruct.terms_and_conditions);

data = b_outs.toByteArray();

obj_outs.close();

b_outs.close(); Docsity.com

Serializing Objects (cont.)

14

/** at this point, byte buffer contains the serialized form of pstruct */

/** reconstruct pstruct as follows */

ByteArrayInputStream b_ins = new ByteArrayInputStream(data);

ObjectInputStream obj_ins = new ObjectInputStream(b_ins);

Serializing Objects

16

 Complication :
Correct handling of other referenced objects. The object to be serialized
must include a copy of all the objects it references, all the objects those
objects reference, and so on. (All these objects have to be included by
the serialized object, because they are part of its total state.)
 Note :
The writeObject() method does not explicitly synchronize on the object
being serialized. If you have multiple threads using the same object, and
one thread can possibly be serializing an object while another thread is
manipulating fields of the same object, you must take steps to be thread
safe (e.g. add explicitly synchronization code, make an object clone
before serializing).

Object Serialization for Classes

17

 Making instances of your classes serializable 
Just add the implements Serializable clause to your class declaration :
 No methods needed (serialization is handled by the defaultWriteObject
method of ObjectOutputStream).
 Deserialization with the defaultReadObject method in
ObjectInputStream.
 Default behavior is good enough, but can be slow, and a class might
want more explicit control over the serialization.

public class MySerializableClass implements Serializable { ... }

The Externalizable Interface

 Differs from Serializable in :

 the amount of control in the serialization process  the extent of customizations

 writeObject, readObject  responsible for serializing only the immediate class.

 Any serialization required by the superclasses is handled automatically.

 Class  { explicitly coordinate with its superclasses to serialize itself }  implementing the Externalizable interface.

 + : Complete, explicit control of the serialization process.

! : Only the class identification of the object is automatically saved by the stream. The class is responsible for writing and reading its contents, and it must coordinate with its superclasses to do so (whether or not the state of superclasses and which fields are stored).

Externalization API

 writeExternal() must encode the data of the object in a form and sequence supported by readExternal().

 Does not support code versioning  you must provide your own versioning approach.

 Above methods are public  security risk (a client may be able to write or read information in the object other than by using its methods).

20

Method (public) Description

readExternal(ObjectInput) The object implements this method to restore its contents by calling the methods of DataInput for primitive types and readObject() for objects, strings and arrays. writeExternal(ObjectOutput) The object implements this method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject() method of ObjectOutput for objects, strings and arrays. For more details consult the Java API.