0% found this document useful (0 votes)
56 views

Unit Ii

The document discusses distributed application architecture and remote method invocation (RMI) in Java. It describes how RMI allows objects in one Java virtual machine (JVM) to invoke methods on objects residing in another JVM. RMI uses stub and skeleton objects to enable remote communication between applications. Stubs act as proxies for remote objects on the client side, while skeletons handle incoming requests on the server side. The document provides steps to create a basic RMI application, including defining a remote interface, implementing it, running the rmic compiler to generate stubs and skeletons, starting the RMI registry, and running client and server code. It also discusses layered and object-oriented styles of distributed application architecture.

Uploaded by

ramyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Unit Ii

The document discusses distributed application architecture and remote method invocation (RMI) in Java. It describes how RMI allows objects in one Java virtual machine (JVM) to invoke methods on objects residing in another JVM. RMI uses stub and skeleton objects to enable remote communication between applications. Stubs act as proxies for remote objects on the client side, while skeletons handle incoming requests on the server side. The document provides steps to create a basic RMI application, including defining a remote interface, implementing it, running the rmic compiler to generate stubs and skeletons, starting the RMI registry, and running client and server code. It also discusses layered and object-oriented styles of distributed application architecture.

Uploaded by

ramyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT II

Remote Method Invocation-Distributed Application Architecture- Creating stubs and

skeletons- Defining Remote objects- Remote Object Activation-Object Serialization-Java

Spaces.

REMOTE METHOD INVOCATION:

The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.

The RMI provides remote communication between the applications using two
objects stub and skeleton.

Creating stubs and skeletons

Stub and Skeleton


RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:

Stub

The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.

Defining Remote objects and Remote Object Activation

Java RMI Example

The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the
rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The
client application need only two files, remote interface and client application. In the rmi
application, both client and server interacts with the remote interface. The client
application invokes methods on the proxy object, RMI sends the request to the remote JVM.
The return value is sent back to the proxy object and then to the client application.

1) create the remote interface

For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named add()
and it declares RemoteException.

import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}
2) Provide the implementation of the remote interface

Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to

o Either extend the UnicastRemoteObject class,


o or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool
invokes the RMI compiler and creates stub and skeleton objects.

rmic AdderRemote

4) Start the registry service by the rmiregistry tool

Now start the registry service by using the rmiregistry tool. If you don't specify the port
number, it uses a default port number. In this example, we are using the port number 5000.

rmiregistry 5000

5) Create and run the server application

Now rmi services need to be hosted in a server process. The Naming class provides
methods to get and store the remote object. The Naming class provides 5 methods.

public static java.rmi.Remote lookup(java.lang.String) throws It returns the reference of


java.rmi.NotBoundException, java.net.MalformedURLException, the remote object.
java.rmi.RemoteException;

public static void bind(java.lang.String, java.rmi.Remote) throws It binds the remote object
java.rmi.AlreadyBoundException, java.net.MalformedURLException, with the given name.
java.rmi.RemoteException;

public static void unbind(java.lang.String) throws It destroys the remote


java.rmi.RemoteException, java.rmi.NotBoundException, object which is bound with
java.net.MalformedURLException; the given name.

public static void rebind(java.lang.String, java.rmi.Remote) throws It binds the remote object
java.rmi.RemoteException, java.net.MalformedURLException; to the new name.

public static java.lang.String[] list(java.lang.String) throws It returns an array of the


java.rmi.RemoteException, java.net.MalformedURLException; names of the remote
objects bound in the
registry.

In this example, we are binding the remote object by the name sonoo.

import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}

6) Create and run the client application

At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the
remote object from another machine, change the localhost to the host name (or IP address)
where the remote object is located.

import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}

For running this rmi example,

1) compile all the java files

javac *.java

2)create stub and skeleton object by rmic tool

rmic AdderRemote

3)start rmi registry in one command prompt

rmiregistry 5000

4)start the server in another command prompt

java MyServer

5)start the client application in another command prompt

java MyClient

Output of this RMI example


Distributed Application Architecture:

Distributed systems are a set of autonomous computers that appears to be a single


coherent system to its users from outside. There are actually two different types of systems
that exist in prospective of computers:

Centralized System :

● A centralized system consists of a single machine.


● All calculations are done by a particular computer.
● Its performance is low as the workload is not divided.
● There is also no machine present in backup if the original computer system fails.

Distributed Systems :

● A distributed system consists of multiple machines.


● All computation work is divided among the different systems.
● Its performance is high as the workload is divided among different computers to
efficiently use their capacity.
● There are systems present in backup, so if the main system fails then work will not stop.
A distributed system contains multiple nodes that are physically separate but mixed
together using the communication networks.
Architecture Styles:
To show different arrangement styles among computers Architecture styles are proposed.

1. Layered Architecture:

In Layered architecture, different components are organised in layers. Each layer


communicates with its adjacent layer by sending requests and getting responses. The
layered architecture separates components into units. It is an efficient way of
communication. Any layer can not directly communicate with another layer. A layer can
only communicate with its neighbouring layer and then the next layer transfers
information to another layer and so on the process goes on.
In some cases, layered architecture is in cross-layer coordination. In a cross-layer, any
adjacent layer can be skipped until it fulfils the request and provides better performance
results. Request flow from top to bottom(downwards) and response flow from bottom to
top(upwards). The advantage of layered architecture is that each layer can be modified
independently without affecting the whole system. This type of architecture is used in Open
System Interconnection (OSI) model.
To the layers on top, the layers at the bottom offer a service. While the response is
transmitted from bottom to top, the request is sent from top to bottom. This method has
the advantage that calls always follow a predetermined path and that each layer is simple
to replace or modify without affecting the architecture as a whole.
2. Object-Oriented Architecture:

In this type of architecture, components are treated as objects which convey information to
each other. Object-Oriented Architecture contains an arrangement of loosely coupled
objects. Objects can interact with each other through method calls. Objects are connected to
each other through the Remote Procedure Call (RPC) mechanism or Remote Method
Invocation (RMI) mechanism. Web Services and REST API are examples of object-oriented
architecture. Invocations of methods are how objects communicate with one another.
Typically, these are referred to as Remote Procedure Calls (RPC). REST API Calls, Web
Services, and Java RMI are a few well-known examples. These characteristics apply to this.
3. Data Centered Architecture:

Data Centered Architecture is a type of architecture in which a common data space is


present at the centre. It contains all the required data in one place a shared data space. All
the components are connected to this data space and they follow publish/subscribe type of
communication. It has a central data repository at the centre. Required data is then
delivered to the components. Distributed file systems, producer-consumer systems, and
web-based data services are a few well-known examples.
For example Producer-Consumer system. The producer produces data in common data
space and consumers request data.
4. Event-Based Architecture:

Event-Based Architecture is almost similar to Data centered architecture just the difference
is that in this architecture events are present instead of data. Events are present at the
centre in the Event bus and delivered to the required component whenever needed. In this
architecture, the entire communication is done through events. When an event occurs, the
system, as well as the receiver, get notified. Data, URLs etc are transmitted through events.
The components of this system are loosely coupled that’s why it is easy to add, remove and
modify them. Heterogeneous components can communicate through the bus. One
significant benefit is that these heterogeneous components can communicate with the bus
using any protocol. However, a specific bus or an ESB has the ability to handle any kind of
incoming request and respond appropriately.
Object Serialization

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It


is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is


converted into an object. The serialization and deserialization process is platform-
independent, it means you can serialize an object on one platform and deserialize it on a
different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class,
and for deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization

It is mainly used to travel object's state on the network (that is known as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark"
Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be
persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by
default.
Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements Serializable interface. Now its objects can
be converted into stream. The main class implementation of is showed in the next code.

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.

Constructor

1) public ObjectOutputStream(OutputStream out) It creates an ObjectOutputStream that


throws IOException {} writes to the specified OutputStream.

Important Methods

Method Description

1) public final void writeObject(Object obj) throws It writes the specified object to the
IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} It flushes the current output stream.

3) public void close() throws IOException {} It closes the current output stream.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an


ObjectOutputStream.

Constructor
1) public ObjectInputStream(InputStream in) It creates an ObjectInputStream that reads
throws IOException {} from the specified InputStream.

Important Methods

Method Description

1) public final Object readObject() throws IOException, It reads an object from the input
ClassNotFoundException{} stream.

2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize
the object. We are saving the state of the object in the file named f.txt.

Persist.java

1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Output:

success

Java Serialization with Inheritance (IS-A Relationship)

If a class implements Serializable interface then all its sub classes will also be serializable.
Let's see the example given below:
SerializeISA.java

1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
10. class Student extends Person{
11. String course;
12. int fee;
13. public Student(int id, String name, String course, int fee) {
14. super(id,name);
15. this.course=course;
16. this.fee=fee;
17. }
18. }
19. public class SerializeISA
20. {
21. public static void main(String args[])
22. {
23. try{
24. //Creating the object
25. Student s1 =new Student(211,"ravi","Engineering",50000);
26. //Creating stream and writing the object
27. FileOutputStream fout=new FileOutputStream("f.txt");
28. ObjectOutputStream out=new ObjectOutputStream(fout);
29. out.writeObject(s1);
30. out.flush();
31. //closing the stream
32. out.close();
33. System.out.println("success");
34. }catch(Exception e){System.out.println(e);}
35. try{
36. //Creating stream to read the object
37. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
38. Student s=(Student)in.readObject();
39. //printing the data of the serialized object
40. System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);
41. //closing the stream
42. in.close();
43. }catch(Exception e){System.out.println(e);}
44. }
45. }

Output:

success
211 ravi Engineering 50000

The SerializeISA class has serialized the Student class object that extends the Person class
which is Serializable. Parent class properties are inherited to subclasses so if parent class is
Serializable, subclass would also be.

Java Serialization with Aggregation (HAS-A Relationship)


If a class has a reference to another class, all the references must be Serializable otherwise
serialization process will not be performed. In such case, NotSerializableException is
thrown at runtime.

Address.java

1. class Address{
2. String addressLine,city,state;
3. public Address(String addressLine, String city, String state) {
4. this.addressLine=addressLine;
5. this.city=city;
6. this.state=state;
7. }
8. }
Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. Address address;//HAS-A
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
Since Address is not Serializable, you cannot serialize the instance of the Student class.
Java Spaces:

Java Spaces can be considered as a library providing a set of methods to help the
developers to build a distributed system that uses the flow of objects model. The system is
not based on the traditional approach using the method-invocation-style protocol.
Otherwise, it uses the flow of objects approach to accomplish the distributed computing
this means the architecture of the distributed system is based on the movement of objects.

The objects can move in and out of the “spaces”. This kind of architecture can sim plify the
remote interfaces of the distributed system. If the system uses the method-invocation-style
design, then the developers will have to design a much more complex remote interface then
the remote interface used in the Java Spaces.

Java Spaces is a technology that makes Java objects easy to do dynamic sharing,
communication, and coordination with each other. Java Spaces hides the low level design
of message communication, objects passing, and consistency maintenance from the users.
Java Spaces is developed based on the Jini technology while Jini is based on the RMI of Java.
The characteristic of Jini is that Jini can let any process residing in any JVM (Java Virtual
Machine) transfer binary code to each other.

Java Spaces is like a marketplace with some clients, sellers, and brokers, etc. For example,
we can use the Java Spaces to build several PC marketplaces by spaces - just analogous to
the physical PC stores in the real world. According to our own design, the sellers can put
the objects containing prices, and order forms, etc., and then request the spaces to notify
the sellers when the objects they put are being read. Each client can search the prices for
the products they specified in those marketplaces.

The design goals of Java Spaces technology are:

Simple

To achieve this goal, Java Spaces only have seven major methods that are usually used.
Those methods are “write”, “read”, “take”, “notify”, “snapshot”, “readBlock ing”, and
“takeBlocking”. The Java Spaces ™ hides many complex issues from de veloper like message
transmission, service lookup mechanism, etc.

Write less code

Most of the server codes are written by Java Spaces so the developers can pay less attention
to the low level stuff. The object transmission mechanism, serialization process,
notification mechanism, and many other procedures are all packed as libraries to be used.
Unified mechanism broadens applications

The unified structure of the programs can easily replicate the programs and execute them.

Legacy interoperability

This goal is achieved because we can reuse the legacy codes by wrapping them in objects
created by Java APIs.

Use Java language to full capabilities

This means to exploit the characteristic of Java. Because Java is a strongly typed
programming language, Java Spaces take the advantage of this to find, match, and reference
Java objects in the spaces of Java Spaces service.

Real objects

The objects stored in Java Spaces are real objects. This means the objects can be data or
classes so the objects can store data, methods, and other objects and so on.

Asynchronous

The providers and requestors of network resources exchange their information asyn
chronously.

Extensible

A variety of implementations should be possible, including relational database and object-


oriented database storage.

Transparent

The same entries and templates must work in the same ways regardless of the
implementation. The entries and templates will be considered the same if all the public
fields are exactly identical.

100% Pure Java

This design goal is to maintain the consistency of this library.


The Operations of Java Spaces:

Write

The write operation will duplicate a copy of entry and place the copy into the space of Java
Spaces service. The original entry object will not be affected by the write operation. This
means the entry can be passed to several write operations without any change. The write
method takes three parameters – an Entry that will be written into the space of the Java
Spaces service, a Transaction that specifies which transaction this write belongs to, and a
long value to notify the Java Spaces service the leasing time of the written object. If the
write operation belongs to a certain transaction, the other operations outside the
transaction will not be able to see the entry used by this write operation until this
transaction being committed.If we specify the leasing time to be Lease. FOREVER,
according to Sun’s implementation, the actual leasing time will be limited to five minutes.
When we want the Java Spaces service to keep the object forever, the only way is to renew
the lease periodically.

Read

The read operation request the Java Spaces service to search through the space for an entry
that matches the template passed to the read operation. This action will not remove the
entry from the Java Spaces service. The read method takes three parameters – an Entry
that specifies the template, a Transaction that specifies which transaction this operation
belongs to, and a long value to specify the time the read operation should be blocked to
wait for the requested object. When the waiting time exceeds, the read operation will
simply return a null value indicating the re quested object is not in the Java Spaces service.
The matching procedure is to match the public fields of the provided Entry template
against the Entry stored in the space of Java Spaces service. We can use the null in the
public field of template to specify this field to be a doesn’t-care field during matching
procedure. The function of null here is like a wildcard character. When the Java Spaces
service tries to find the matching entry, the null field will all be considered as successful
matching. If the second argument of the read is null, this means this read operation is a
standalone operation – it itself is a single operation transaction. There might be several
entries match the template, according to the Java Spaces Specification, the Java Spaces
service will not guarantee each time the read operation will get the same entry from the
space. We will get one of the matching entries from the spaces either from written entry in
the same transaction or the entry outside the transaction. This means we can not design a
system relies on assuming the Java Spaces service will return the same entry whenever we
execute the read request. There is a similar operation – readIfExists. The main different is
the readIfExists operation will return immediately no matter the request entry is in the
space or not. But there is an exception; if the matching entry is in the same transaction of it
self, the readIfExists operation will wait if the programmer specifies a waiting period until
the waiting period expires.

Take

The take operation request the Java Spaces service to search an entry stored in the space
that matches the public field specified by the template passed to the take operation. If the
Java Spaces service finds the matching entry, it will remove the matching entry from the
space of the Java Spaces service and return the entry. If there are many matching entries in
the space of the Java Spaces service, the service will choose one from them without any
regulation. So if our program takes the entries successively from the space, we can not
expect what is the order of entries being returned. The relationship between take and
takeIfExists are similar to read and readIfExists. So the takeIfExists will return null
immediately if there is no entry matches the provided template and the only exception is if
the takeIfExists belongs to a transaction, the takeIfExists will wait if the developer specified
a waiting time.

Notify

The notify operation requests the Java Spaces service to notify the listener when any
participant writes an entry that matches the provided template. The notify takes five
parameters – an Entry that specifies the template, a Transaction object that indicates that
the notify operation will not occur within a transaction, a RemoteEventListener that is an
object that receives the remote events from the space of the Java Spaces service, a long
value for the leasing time to specify the period of time the Java Spaces service should
maintain the notification, and a Marshaled Object that is an object that the Java Spaces
service provides to the remote listener as part of the notification.

Snapshot

Originally, every time we pass the template to the methods of Java Spaces service such as
read, write, take, etc., the template must be serialized before it being transferred to the
space of Java Spaces service. If the same template is used so many times, the overhead of
serialization can not be disregarded. To avoid this kind of overhead, we can use snapshot to
“snapshot” an entry we provide and return a specialized entry – a snapshot of entry. This
specialized entry can be passed to the read, write, and take, etc. and avoid the overhead of
serialization. The restriction of 8 the usage of snapshot is the specialized entry can only be
used within the Java Spaces service that generates it.

You might also like