Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

object serialization and rmi

VIEWS: 12 PAGES: 35

jjava programming

More Info
									Object Serialization and RMI




         Your IT Partner
Objectives
After completing this chapter, the student will be able to:

 •   Explain object persistence and the need for it
 •   Explain the difference between storing primitive
     datatypes and Java objects
 •   Explain object serialization
 •   Explain Java’s support for object serialization
 •   Write Java programs to store Java objects into a
     file and retrieve them from the file
 •   Write Java programs to transmit and receive
     Java objects over a network


                                            CMC Limited
                                      Objectives contd..




•   Explain Remote Method Invocation (RMI)
•   Explain RMI architecture
•   Explain Java’s support for RMI
•   Explain distributed processing
•   Write simple RMI applications
•   Write applet programs for remote method
    invocation




                                     CMC Limited
Introduction
•   The lifetime of an object is until the point it is garbage
    collected or until the program stops.

•   In the case of an applet object, its lifetime is until the
    applet is closed or until the browser program in which
    the applet is running is closed.




                                              CMC Limited
Java Garbage
•   An object becomes garbage, the moment the
    program stops referencing it.

            class ExamleClass
                        {
                         ------------
                         ------------
                        }
                  ------------
                  ------------
                  public static void main(String[] args)



                                        CMC Limited
Storing Objects
•   Objects can be stored into a file on the fixed disc or it
    can be sent to a remote system over the network for
    some kind of processing.

•   If an object is to be written into a file or onto a
    network, we can do so by writing the primitive type
    data fields into the file, or onto the network.

•   You can retrieve these data and reconstruct your
    original object.




                                             CMC Limited
Object Persistence and Serialization
•   Object persistence is the ability of an object to exist
    even after the program that created it finished its
    execution.

•   An object becomes persistent when its state is
    recorded into a permanent storage medium.

•   Object can be recorded by recording its state into a
    file.




                                            CMC Limited
               Object Persistence and Serialization contd..

•   Object serialization is the process of recording an
    object by writing the state values and the other object
    attributes.

•   It is called serialization because the inmemory layout
    of the object is converted into an ordered series of
    bytes.

•   Deserialization is the reverse process               of
    reconstructing the object from a stream.

•   Java provides classes and methods both for
    serialization and deserialization.



                                            CMC Limited
Java’s Support for Object Serialization
•   To enable serialization and deserialization we need
    the following functionalities:

    •   A mechanism for converting the inmemory layout
        of an object into an ordered series of bytes, which
        can be written into a stream for storage in a file or
        for transmission over a network.
        • A mechanism for reconstructing the object
            from the stream.
        • A mechanism to initiate serialization and
            deserialization.



                                             CMC Limited
            Java’s Support for Object Serialization contd..

Serializable Interface
•   This interface is defined as shown below:

    public interface Serializable
       {
             }

•   No methods are declared in this interface.
•   When a class declares that it implements Serializable
    interface, it only means that it can take part in the
    serialization process.
•   An object that implements Serializable interface can
    be serialized by an external object, usually by a type
    of stream object.

                                           CMC Limited
            Java’s Support for Object Serialization contd..

Externalizable Interface
•   The definition for the Externalizable interface is
    shown below:

    public interface Externalizable extends Serializable
       {
           public void writeExternal(ObjectOutput out)
                                 throws IOException;

          public void readExternal(ObjectInput in)
                     throws                 IOException,
       ClassNotFoundException;
         }


                                           CMC Limited
           Java’s Support for Object Serialization contd..

DataOutput Interface
•   The DataOutPut interface supports methods for
    writing primitive data types.

•   Example: writeDouble( ) method writes data type
    double, writeBoolean() method writes data type
    boolean etc.




                                        CMC Limited
            Java’s Support for Object Serialization contd..

ObjectOutput Interface
•   This interface is defined as shown below:
    public interface ObjectOutput extends DataOutput
        {
        public void writeObject(Object obj) throws
       IOException;
        public void writeObject(int ) throws IOException;
        public void writeObject(byte[] b) throws
       IOException;
        public void writeObject(byte[] b, int off, int len )
       throws IOException;
        public void flush( ) throws IOException;
        public void close( ) throws IOException;
        }

                                            CMC Limited
            Java’s Support for Object Serialization contd..

ObjectOutputStream Class
•   The definition for ObjectOutputStream class is given
    below:
    public     class    ObjectOutputStream     implements
        ObjectOutput
         {
         public ObjectOutputStream(OutputStream os)
    throws IOException, StreamCorruptedException;
         public void writeObject(Object obj)      throws
        IOException;
         public void close( ) throws IOException;
                            public void flush( ) throws
        IOException;


                                          CMC Limited
            Java’s Support for Object Serialization contd..

ObjectInputStream Class
•   ObjectInputStream class has only one constructor
    and it takes an InputStream object as parameter.

•   Following are some of the class methods:
    • ObjectInputStream(InputStream in) // constructor
    • readObject( )
    • close( )
    • available(     )    //    no    counterpart    in
        ObjectOutputStream class
    • readInt( )
    • readUTF( )
    • defaultReadObject( )


                                         CMC Limited
Serializing Object into a File and
Deserializing It
•   To serialize an object obj of some class type, say
    class xyz into a file, the first step is to create a
    FileOutputStream object to create a file and connect
    the stream object to the file.
    • FileOutputStream fos = new FileOutputStream(“
        example.file” );
•   The next step is to create an ObjectOutputStream
    object and chain it to the FileOutputStream object
    fos:
    • ObjectOutputStream           oos       =      new
        ObjectOutputStream(fos);

                                         CMC Limited
    Serializing Object into a File and Deserializing It contd..

•   The third step is to invoke the writeObject( ) method
    of the ObjectOutputStream class with obj as
    parameter:
    • oos.writeObject(obj);
    • oos.flush( );
•   To deserialize this object from the file example.file,
    the first step is to declare obj of the same class type
    • xyz obj;




                                            CMC Limited
Object Serialization and Deserialization
Example
•   Example program for serialising objects into a file:

    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    import java.util.Date;
    public class WriteDate
        {
       public static void main(String[] args)
          {
        try
             {

                                                CMC Limited
Object Serialization and Applets
•   Object serialization and deserialization can be done,
    not only by application programs, but also by applet
    programs.
    import java.io.FileInputStream;
    import java.io.ObjectInputStream;
    import java.util.Date;
    import java.awt.Graphics;
    public class ReadDate extends java.io.applet.Applet
•   The above applet has to be viewed through the
    appletviewer. The reasons are:
    • Ordinary browsers do not support serialization.
    • A downloaded applet cannot access local
       resources because of security restrictions.
                                          CMC Limited
Serializing Your Own Objects
•   You can serialize and deserialize objects of your own
    classes as long as the object does not refer to a peer
    object.
•   You have to declare that your class implements the
    serializable interface.
•   A program to serialize objects of user defined class:

    import java .io.FileOutputStream;
    import java.io.ObjectOutputStream;
    public     class     SerializableClass    implements
       java.io.Serializable
                       {


                                             CMC Limited
Customising Object Serialization
•   Definition of a date class with methods to read and
    write Date object as three integers:

    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class TestDate implements Serializable
       {
       transient GregorianCalendar myDate;
       public void newDate( )
         {



                                          CMC Limited
Remote Method Invocation (RMI)
•   RMI makes possible to build modular and
    manageable applications.
•   RMI allows to call object methods located remotely,
    sharing resources and processing load across
    systems.
•   The three new important features with the release of
    Java 5.0 include:
    • Support for dynamic stub generation
    • RMI over SSL
    • The ability to launch a Java RMI sever as an
       extended Internet service (xinetd) daemon in Unix
       systems

                                         CMC Limited
                Remote Method Invocation (RMI) contd..

•   RMI features are as follows:
    • Remote method call
      o Pass Java objects as parameters
    • Name lookup & binding (location service)
      o Find and bind to remote objects
    • Easy multi-threaded servers
    • Remote object activation
      o server objects occupy memory only when
          active
    • Automatic distributed garbage collection
    • Dynamic class loading over the net




                                    CMC Limited
Java's Support for RMI
•   Java provides tools, interfaces and classes to
    support RMI. It provides two tools viz.
    • rmic.exe
    • rmiregistry.exe
•   These tools are available in the java\bin directory.
    The syntax for these commands are:
    • C:\> rmic Example Class
•   The syntax for rmiregistry command is
    • C:\> rmiregistry 109




                                         CMC Limited
                              Java's Support for RMI contd..

java.rmi Package
•   The java.rmi package       contains   the   following
    interfaces and classes:

       interface Remote
       class Naming
       class RMISecurityManager




                                          CMC Limited
                          Java's Support for RMI contd..

java.rmi.dgc Package
•   The java.rmi.dgc package contains the following
    interfaces and classes:

      interface DGC
      class Lease
      class VMID




                                      CMC Limited
                            Java's Support for RMI contd..

java.rmi.registry Package
•   This package contains the following interfaces and
    classes:

       interface Registry
       interface RegistryManager
       class LocateRegistry




                                        CMC Limited
                            Java's Support for RMI contd..

java.rmi.server Package
•   This package contains the following interfaces and
    classes:

       interface LoaderHandler
       interface RMIFailureHandler
       interface RemoteCall
       interface RemoteRef
       interface ServerRef
       interface Skeleton
       interface Unreferenced
       class LogStream
       class ObjID
       class Operation

                                        CMC Limited
RMI and Object Serialization
•   Objects passed as parameters and the returned
    object must be serializable.

•   Serialization allows to transmit complete tree
    structure of objects as a byte stream over the
    network to the remote server system.

•   RMI system allows these objects to exist on the
    remote server system.




                                      CMC Limited
Creating a Remote Object
•   As Remote interface doesn’t have any method, you
    have to create a new interface for your object which
    extends the Remote interface as shown below:

     public       interface   SomeInterface     extends
      java.rmi.Remote
         {
          ------------
          ------------
        }




                                         CMC Limited
An RMI Example
•   The server application defines a remote method and
    creates a remote object.
•   The remote method returns the current system date
    of the server system as a Date object.
•   The client application running on a remote client
    system invokes the remote method.
•   The remote method on server system will be
    executed.
•   It returns the current date object of the server system
    and transmits it to the client.
•   Then by invoking the remote method, the client will
    receive a Date object.


                                            CMC Limited
Program Explanation
•   By       extending      UnicastRemoteObject,    the
    CalendarImpl object will become exported.
•   It will become ready to be used outside the machine
    in which it was created.
•   A remote object extends UnicastRemoteObject, is
    exported      in     the     constructor   of   the
    UnicastRemoteObject class.
•   The CalendarImpl class defines the remote method
    getDate().
•   This method returns the current date and time as a
    Date object.



                                         CMC Limited
The Client/Server Architecture in RMI
•   The first function is to locate remote objects.
•   To obtain references to remote objects applications
    can use one of the two mechanisms.
•   An application can register its remote objects either
    with RMI’s simple naming facility, the rmiregistry, or
    the application can pass and return remote object
    references as part of its normal operation.
•   The second function is to communicate with remote
    objects.
•   The RMI handles the details of communication
    between remote objects; looks like a standard java
    method invocation to the programmer.


                                           CMC Limited
Dynamic Class Loading
•   Java applications and applets are made up of several
    class files.
•   At run time these .class files are loaded into the
    memory for execution.
•   If an application or applet is importing classes from
    any system provided or user created packages,
    those classes are also loaded into memory.
•   Class loaders are used to load the class files into
    memory at runtime.
•   The two types of class loaders we have used so far
    (knowingly or unknowingly) are the applet class
    loader and the default class loader.


                                          CMC Limited
Another Simple RMI Example
•   In this example, we assume that both the client and
    server are running on the same machine, the client in
    the client DOS window and the server in the server
    DOS window.
•   We will first create a remote interface in which we will
    declare our remote method.
•   The method takes a string type parameter and
    returns a string type value.
•   The returned string value is synthesized using the
    parameter string.
•   The client invokes the remote method by passing a
    string value.


                                            CMC Limited

								
To top