0% found this document useful (0 votes)
6 views24 pages

Java RMI

The document provides an overview of Remote Method Invocation (RMI) in Java, detailing its role in creating distributed applications that allow remote method calls between objects in different Java Virtual Machines (JVMs). It also discusses object persistence and serialization, explaining how Java objects can be stored and retrieved, and introduces distributed computing, its components, characteristics, advantages, and challenges. Finally, it touches on middleware services and Remote Procedure Call (RPC) mechanisms for client-server communication in distributed systems.

Uploaded by

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

Java RMI

The document provides an overview of Remote Method Invocation (RMI) in Java, detailing its role in creating distributed applications that allow remote method calls between objects in different Java Virtual Machines (JVMs). It also discusses object persistence and serialization, explaining how Java objects can be stored and retrieved, and introduces distributed computing, its components, characteristics, advantages, and challenges. Finally, it touches on middleware services and Remote Procedure Call (RPC) mechanisms for client-server communication in distributed systems.

Uploaded by

adarshamu2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program Name :

B.C.A. Semester: VI

Course :ADVANCEDJAVA AND J2EE

UNIT III

I Study Material |
RMI Distributed Applications

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

object unning in another JVM. The RMI provides remote communication


between the
applications using two objects stub and skeleton.

With RMI, a Java programmer can


create a publicly accessible remote server
object.
This object seamless client-server communications through simple
iacilitates
method
calls on theserver object. Client programs can
communicate directly with the server
object and with each other using a URL and HTTP.

Working o!RM!
The cormmunicaion between client and server is handled by using two intermediate
objecis: Stuboiject (on client side) and Skeleton object (on server-side) as also can be
depictei from below media as follows:

Working of RMI
Client Server

onSrver!

Internet

2|Pae
A high-level overview how client and
of server communicate through remote objects
using RMI isdescribed below.

1. Define the Remote Interface:


You define a Java interface that extends the
[Link] interface.
• Each method in this interface must declare
[Link] in
its throws clause to handle
remote method invocation errors.
This interface defines the methods that the client
can invoke on the
remote object.
2. Implement the Remote Object:
• You implement the remote interface on the server side. This class will
extend
[Link] or
[Link]
and implement the methods cdefined in the
remote interface.
The server class provides the implementation for tlhe methods declared in
the remote interface.

3. Create and Start the RMI Registry:

The server creates an RMI registry, which acts as a centra! registry for
remote objects. The registry listens for incoming requests Gn a specific
port.

You can start the RMI registry from the command line using the
rmiregistry toolprovided with the JDK.
4. Bind the Remote Object to the Registry:

The server binds the remote object to the RMl registry using a unique
name.

This makes the remote object accessible to clients by its name.


5. Lookup the Remote Objecton the Client Side:

The client looks up the remote object in the RMIregistry using the naming
service ([Link] [Link].
The client obtains a reference to the remote objeci, vhich it can then use
to invoke remote methods.

3| Pag
6. nvoke Remote Methods:

The client invokesmethods on the remote object referenceobtained from


the RMI registry.

RMI handles the communication details, including parameter organizing,


network communication, and error handling, transparently to the client.

7. iiandleExceptions:

Both the client and server should handle


[Link] and
any other application-specific exceptions that may occur during remote
method invocation.

By following these steps, you can establish communication between a client and a

server using remote objects in Java RMI. This mechanism allows for transparent
communication between distributed Java applications, enabling method invocation
acrossditferent JVMs and physical machines.

ObiertjsrsistenCe and serialization


Objeci persistence and serialization are twNO related concepts in Java that deal with
the storageand retrieval of Java objects a persistent
in form, typically to a file or over
a network.

Objecr Persistence:

Object persistence refers to the ability to store and retrieve objects beyond the
lifetime of the application's execution.

With object persistence, the state of an object can be saved to a persistent

storagemedium (such as a database,file system,or cloud storage) and later can


be restored, allowing the application to work with the same data acrossdifferent
runs or even different instances of the application.

4|Page
Persistence is essential for applications that need to maintain data integrity,

share data between multiple users or instances, or store data ior long-term

use.

Serialization:

Serialization is the process of converting an object into a strean of bytes, which


can be easily stored or transmitted and later reconstructed to create an identical

copy of the original object.

In Java, serialization is achievedby implementing the Serializable interface, which


is a marker interface indicating that the class is serializable.

Serializable objects can be written to an output stream (e.g., a file or network


socket) using an ObjectOutputStream, and later read from an input stream using
an ObjectlnputStream.

Serialization allows objects to be easily stored to disk,transmitted overa network,


or saved to a database, enabling object
persistence.

Hence object persistence and serialization provide a powerful mechanism for storing
and retrieving Java objects in a persistent form. They are commonly Used in various
applications, including data storage, caching, messaging systems, and distributed
computing. However, it's essential to consider factors like performance,data integrity,
and security when designing and implementing object persistence and serialization
solutions.
Introducion to Distributed Computing

Distributed computing is the method of making multiple computers work together to

solve a common problem. It makes a computer network appear as a powerful single

computer that provides large-scale resources to deal with complex challenges.

It is a coliecion of independent components located on different machines that share

messages with each other in order to achieve common goals.

Distributed computing refers to a system where processing and data storage is

distributed across multiple devices or systems, rather than being handled by a single

central device. In a distributed system, each device or system has its own processing

capabilities and may also store and manage its own data. These devices or systems

work together to perform tasks and share resources, with no single device serving as

the central hub.

One exainpleof a distributed computing system is a cloud computing system, where

resourcessuch as computing power,storage, and networking are delivered over the

Internet and accessed on demand. In this ty pe of system, users can access and use

shared res0tes through a web browser or other client software.

Cornponents

There arc several key components of a Distributed Computing System

Devices orSystems: The devices or systems in a distributed system have their

GWi processing capabilities and may also store and manage their own data.
Metwork: The network connects the devices or systems in the distributed

systen, allowing them to communicate and exchange data.

6|Page
Resource Management:
Distributed systems often have some type

of
resource management system in place to allocate and manage shared
resourcessuch as computing power,
storage, and networking.
The architecture of a
Distributed Computing System is typically a
Peer-to-Peer
Architecture, where devices or systems can act as both clients and servers and
communicate directly with each other.

Characteristics

There are several


characteristics that define a
Distributed Computing System
Multiple Devices or
Systems: Processing and data storage is
distributed
across multiple devices
or systems.
Peer-to-Peer Architecture: Devicesor systems in a distrbuted
[Link] can act
as both clients and servers, as they
can both request
andprovide services to
other devices or systems in
the network.
. Shared Resources:
Resources such as
computing puwEr, Siorage,
and
networking are shared among the

. HorizontalScaling: Scaling a
devices or systems in

distributed computing
the netiwork.

system typically involves


adding more devices or
systems to the network to
increase processing
and
storage capacity. This can be
done through
hardware upgrades or by
adding
additional devices or
systems to the network..

Advantages and Disadvantages

Advantages of the Distributed Computing System are:

Scalability: Distributed
systems are generally
more scalable thancentralized
systems, as they can easily add new devices or systems lo the
network to
increase processing and storagecapacity.

|Pase
ikuliubility: Distributed systems are often more reliable than centralized

systems, as they can continue to operate even if one device or system fails.

Ilexibility: Distributed systems are generally more flexible than centralized

systens, as they can be configured and reconfigured more easily to meet

chnging computing needs.


There are a few limilations to Distributed Computing System

Cundexity: Distributed systems can be more complex than centralized

systems, as they involve multiple devices or systems that need to be


cOordinated and managed.

Security:It can be more challenging to secure a distributed system, as

security measures must be implemented on each device or system to ensure

th security of theentire system.

Gr(ance: Distributed Systems may not offer the same level of

performance as centralized systems, as processing and data storage is

distributed across multiple devicesor systems.

Applicaiot:

Distribued Computing Systems have a number of applications, including:

Ciuud Computing: Cloud Computing systems are a type of distributed

Computing system that are used to deliver resources such as computing

powT, storage, and netWorking over the Internet.


#ea-u-Peer Networks: Peer-to-Peer Networks are a type of distributed

computing system that is used to share resources such as files and computing

power among users.

8|Page
Distributed Architectures: Many modern computing systems, such as

microservices architectures, use distributed architectures to distribute


processing and data storageacrossmultiple
devices orsystems.

Challenges of Distributed
Systems
While distributed systems offer many
advantages,they also present
that must be [Link] somechallenges
challenges include:
Network latency: The communication
network distributed in a
system can
introducelatency, which can
affect the
performance of the system.
Distributed
coordination: Distributed systems require
the nodes, which coordination among
can be challenging due to the distributed nature of the
system.

Security: Distributed systems are more


vulnerable to seurity threats
centralized than
systemsdue to the
distributed nature of the
system.
Data consistency:
Maintaining data
consistency across muitipie nodes
distributed
in a
system can be
challenging.

Example of a Distributed
. System
Any Social Media can
have its
Centralized
Computer Network as its
Headquarters and computer
systems that can be accessed by any user and
using their
services will be the Autonomous
Systems in the Distributed
Architecture. System

9|Pae
Distributed System

(oc ate acic:&

corauCI

Disriuted System Software: This Software enables computers to

coUrdinate their activities and to share the resources such as Hardware,

Software, Data, etc.

Daiibase: It is used to store the processed data that are


processed by each
Nude/Sysiem of the Distributed systems that are connected to the
Centaized network.

Working of
Distributed System

LstrtLled

Conpute
Conpsty

|
10 Page
As we can see that each Autonomous System has a common Application that

can have its own data that is shared by the Centralized Database System.

To Transfer the Data to Autonomous Systems, Centralized System should be


having a Middleware Service and should be connected to a Netvork.
Middleware Services enable someservices which are not DresCnt in the local

systems or centralized system default by acting as an interface between the


Centralized System and the local systems. By using components of
Middleware Services systems communicate and
manage data.
The Data which is been transferred through the database
will be divided
into
segments or modules and shared
with Autonomous
systems for processing.
The Data will be processed and
then will be transferred
to the Centralized
system through the network
and will be stored in the daidbase.

RPC Implementation Mechanisn in Disriiuted


System
RPC is an effective mechanism for building
client-server systems that are
distributed. RPC enhances the
power and ease of
programming of the
client/server computing concept. lIt's a protocol that
alows one software to
seek a service
from another
program on another
compUter in a network
without having to know
about the network.
The software that
request is calledaclient, makes the
and the program that
provides the service is
aserver. called

The calling
parameters are sent to the
remote process during a
Procedure Call, and the Remote
caller waits for
a
response irom ihe
[Link] flow of remote
activities during an RPCcall
systems is depicted
between wo networking
in the diagram below.

11 |PaBe
(5..:t

elt

Senakie 'iruspareney:
• Syuiace iransparency:This implies that there should be a similarity between the
remote provess and a local procedure.
Senautic iransparency:This implies that there should be similarity in the
semantics
i.e. mcmy of a remote process and a local procedure.
Worki:y 0 RPC:
There are S clettents used in the working of RPC:
Cint
ClhentStub
RPC Ruie
Server Sub
Server

12 |
Page
Client: The client process
initiates RPC. The client
makes a standardcail, which
a correlated triggers
procedure in the client stub.

Client Stub: Stubs are used by


RPC to achievesemantic
transparency. The client calls
the client stub. Client stub
does the following tasks:

The first task


performed by client stub is when it receives a requesi
from a client, it
packs(marshalls) the parameters and
required
specificaiions of
remote/target
procedure in a message.

The second task performed by the client stub is upon receiving the result
values after
execution,
it unpacks
(unmarshalled)
those results and sends
them to ihe Client.

13 |P as
RPC Runtime: The RPC runtime is in charge of message transmission between client

and server via the network. Retransmission, acknowledgement,


routing, and
encryptionare all tasks performed by it. On the client-side, it receives theresult values
in a message from the server-side, and then it further sends it to the client stub

whereas, onthe server-side, RPC Runtime gotthe same message from theserverstub

when hen i íorwards to the client machine. It also accepts and forwards client

machine call request messages to the serverstub.

Serve: Sub:Serverstub does the following tasks:

The first task performed by serverstub is that it unpacks(unmarshalled)the call request


message which is received from the local RPC Runtime and makes a regular call to
invoke the required procedure in the server.

The second iask performed by server stub is that when it receives the server's
procedure cxecuion result, it packs it into a message and asks the local RPC Runtime
to iransmit it to the client stub where it is unpacked.

Servei:After receiving a call requestfrom the client machine, the serverstub passes it

tothe server. The execution of the required procedure is made by the server and
finaliy, iL returns the result to the server stub so that it can be passed to the client

machine using the local RPC Runtime.

RPC iucess:
. The client, the client stub, and one instance of RPC Runtime are all running on the
client nachine.

A client initiates a client stub process by giving


parameters as normal. The client stub
acquiresstorage in the address space of the client.

14 |
Page
• At this point, the user can accessRPC by using a normal Local Procedural Call. The
RPC runtime is in charge of message transmission between client and server via the
network. Retransmission, acknowledgment, routing, and encrvption are all tasks
performed by it.

On the server-side, values are returned to the server stub,


afier the completion of
serveroperation, which then packs (which is also known
as marshaling) the return
values into a message. The transport
layer receives a message from
The resulting message is transmitted the server stub.
by the transport layer to
the cient transport
layer, which then
sends a message back to the
client stub.
The client stub unpacks (which is
also known as
arguments in the resulting packet, unmarshalling)the return
and the execution process
at this point. relurns io the caller

Client Waii for resuit

Cailre.2cte

3NOCCure

Recuest

Server Call iocal proceiu:s


and reiurn results

15 |
Pagc
SaAS2

When the client process requests by calling a local procedure then the procedure
will pass the arguments/parameters in requestformat so that they can be sent in a

message Lo the remote server. The remote server then will execute the local

pocedure based on the request arrived from the client machine) and after
call (

EAecution fnaily returns a response to the client in the form of a message.


Till this

time the client is blocked but as soon as the response comes from the serverside it

will be able to find the result from the message. Insome cases, RPCs can be executed
asynchronously also in which the client will not be blocked in waiting for the

response.
The paraneLers can be passed in two ways. The first is to pass by value, whereas
tte secOnd is to pass by reference. The parameters receiving the address should be
pointers when we provide it to a function. In Pass by reference, a functionis caled

using pointers to pass the address of variables. Call by value refers to the method of

sending variables' actual values.


parameter
The language designers are usually the ones who decide which
passing

method Itis sometimes dependent on the data type that is being provided.
to uulize.

Iniegers and other scalar types are always passed by value in C, whereas arrays are
always passed by reference.

RMIArchitecture
Java communication
The Rer)ote Method Invocation (RMI)architecture in facilitates

between Java objects residing in different Java Virtual Machines (JVMs) over a

16 |Pa&e
network. It allows objects to invoke methods on remote objects as if they were local

objects. The RMI architecture typically involves several componcnis ord follows a
client-server model:

[Link]

• Interface:

The remote interface isa Java interface that


defines the methods that can be
invoked remotelyby clients. It extends
the [Link] interface.
.Each method in the remote interface must
declare
[Link] in
its throws clause to handle remote method invocation errors.
2. Remote Object
Implementation:
The remote object implementation is a Java class that rGuides the actual
implementation of the methods defined in the remoie intetace.
• This class typically extends
[Link]
implements [Link].

.It is responsible for executing the methods invokedrernotrly by


¿ilents.
[Link] Registry:

. The RMI registry is a simple naming service provided by Java RMI that allows
clients to look up remote by name.
. It acts as a central registry
objects

where remote objects are bound to nomes, making


them accessible to clients.

The servercreates an RMIregistry, and clients use it to locale remote objects.

4. Client:

.The client is the application or component that initiates communication with


remote objects.

17 |Pae
it oba1b àreference to theremote object from the RMI registry using the naming

service provided by [Link] [Link]. Locate Registry.

.Once it has the reference, the client can invoke methods on the remote object as

if it were a local object.

[Link] and Unmarshalling:


RMIhandlesthe marshalling (serialization) and unmarshalling (deserialization) of

method parameters and return values transparently to the client and server.

R2etnod gaiameters and return values are automatically serialized into a stream

of bytes before being transmitted over the network and deserialized back into

objects at the receiving end.

G. Neink CoHunication:

.RM uses TCP/!IP as the underlying network protocol for communication between

ihe clieni and server JVMs.

. itestallishes a connectionbetween the client and serverJVMs, allowingthem to

evmethod invocations and data.

Importance of RIMI Registry

.RMI registry is a namespace on which all server objects are placed. Each time

the server creates an object, it registers this object with the RMIregistry

(usiny its t) crteBind() methods). These are registered using a unique name known

as bind name. t alows remote clients to get a reference to these objects.

|
18 Paee
To invoke a remote object, the client needs a referenceof that obijeci. At tlhat time,the
client fetchesthe object from the registry using its bind name (its!n; 'n'u)method).
The following illustration explains the
entire process -
Irvccs rire m2t0s using:
fetched je:

using
chs

the

obje
lookup()
ct

tron

the
-
reis!r

Goals of RMI

Following are the goals of RMI -


. Tominimize the complexity of the application.

• To preserve type safety.

• Distributed garbage collection.

19|ase
Miuithze the difference between working with local and remote objects.

Callback lmplementation in RMI

An RMI Cal!back occurs when the client of one service passes an object ,that is the

pro:,. iuf htier service. The recipient can then call methods in the object it

received,and be calling back (hence the name) to where it came from

Wiuh RMI,a Java programmer can create a publicly accessible remote server object.

This object iaciilases seamless client-server communications through simple method

calls u:ihe server object. Client programs can communicate directly with the server

object andwith each other using a URL and HTTP.

Developing Simple RMI application


In any RM
retur :
these ipiher
application, the server receives

[Link]
and
this

returns
a request from a client,

example, the request specifies two numbers. The server adds


the Sum.
processes it, and

Step One: Enter and Compile the Source Code


This auplicaric u5es four source files.

tb:it ile, AúdServerintí.java, defines the remote interface that is provided


by itie server. It Contains one method that acceptstwo double arguments and returns
their [Link] renote interfaces must extend the Remote interface, which is part of

[Link]. Remote defines no members. Its purpose is simply to indicate that an


interlace uses remote methods. All remote methods can throw a RemoteException.

inport [Link].',

public interface AddServerlntf extends Remote

(double add (double d1, double d2)throws RemoteException;

20 |
Pa&e
The second source file, [Link],implements
the remole interface.
The implementation of the add() method is direct. All remote objects must extend
UnicastRemoteObject, which provides functionality that is needed to make objects
available from remote machines.

import [Link].;
import [Link].*;
public class
AddServerlmplextends Unicast RemoteObjectimplements AddServerlntf

public AddServerlmpl()
throws RemoteException (}
public double add (doubled1,
doubled2) throws Remote
Exception
d1 + d2;
{return

The source file, [Link],


third
contains the main program for
the server
machine. Its primary function is to
update the RMl registry on that
done by using the rebind() machine. This is
method of the Naming class
(foind in [Link]). That
method associates a name with an
object reference. The first
argument to the rebind()
method is a string that names the server as "AddServer".Its second
referenceto an argument is a
instance of AddServerlmpl.

21 | a
import [Link].*;
import [Link].*;
public class AddServer

public static void main(String argsl)

tiy(
AddServerlmpl addserverlmpl= new AddServedmpl();
Naming rebind("AddServer", addServerlmpl);
System,[Link]("Server is running...");

catch (Exception e)
([Link]("Exception:"+e);

The fourth source file, [Link], implements the client side of this

distributed application. [Link] requires three command-line arguments. The


first is the IP Jddress or name of the server machine. The second and third arguments
are the two nunbers that are to be summed.

Theapplication begins by forming a string that followsthe URL Syntax. This URL
uses therniprotocol. The string includes the lP address or name of the server and the

string "AddServer". The program then invokes the lookup() method of the Naming
class. This method accepts one argument, the rmi URL, and returns a reference to an
object of type AddServerlntf. All remote method invocationscan then be directed to

this object.

The proyram continues by displaying its arguments and then invokes the remote

add()mehod, The sumis returned from this method and is then printed.

|
22 Page
importjava,rmi.";
public class AddClient

public static void main(String args()

try {

String addServerURL="rmi://" + args [0]+"/AddServer";

AddServerlntf addServerlntf = (AddServerlnt) [Link] (addserverURL);


System,gut,printIn("The first number is: "+args[1);
double d1 = Double,valueOf(args[1]).doubleValue);
[Link]("The second number is: "+ args (2);
double d2 = Double,valueOf(args(2]).doubleValue();
[Link]("The sum is:"+ addServerlntf,add(d1, d2):

catch (Exception e)

[Link],printin("Exception: "+ e); )

Compile all the foursource code file using javac.

Step Two: Generate a Stub


Next we need to generatethe necessary stub. In the context of RMI, a stub is a Java

object that resides on the client machine. Its function is topresent the same interfaces

astheremote server. Remote method calls initiated by the client are actually directed

to the stub,The stub works with the other parts of the RMI system to formulate a

request that is sent to the remote machine.

23 |P
A remote method may accept arguments that are simple types or objects. All of

this informationmust be sent to the remote machine. That is, an object passed as an

argument to aremote method call must de serialized and sent tothe remote machine.

If a response must be returned to the client, the process works in reverse. The
serialization and deserialization facilities are also used if objects arereturned to aclient.

To generate a stub, we use a tool called the RMIcompiler, which is invoked from
the comnand line, as shown here:

rmic AddServerimpl

This comrnand generates the file AddServerlmpl_Stub.class. When using rmic,

be sure that CLASSPATH is set to include the current directory.

Step Three: InstallFiles on the Client and ServerMachines

Copy [Link], AddServerlmpl [Link], and [Link] to a

directory [Link], and [Link] to a directory on the servermachine.

RMI has techniques for dynamic class loading, but they are not used by the

example at hand. Instead,all of the files that are used by the client and server

applications must be installed manually on those machines.

Step Four:Start the RMII Registry on the Server Machine


Java SE 6 provides a program called rmiregistry, which executeson the servermachine.
It maps names to object references. First, check that the CLASSPATH environment

variable includes the directory in which your files are located. Then, start the RMI
Registry from the command line, as shown here:

start rmiregistry

When this command returns, a new window has been created. This window must be
open until experimentingwith the RMI done. is

24 | Pate
Step Five: Start the Server

The servercode isstarted from thecommand line, as shown here:

java AddServer

Recall that the AddServer code instantiates AddServerlmpl and registers that
object with the name "AddServer".

Step SixX: Start the Client

The Add Client softwarerequires three arguments: the name or


IP address of the server

machine and the two numbers that are to be summed together. We may invoke it from
the command line by using one of the two formats shown here:

java AddClientserver189

java AddClient [Link] 8 9

In the first line, the name of theserver is provided. The second line uses ils IP address
([Link])

We can try this example withoutactuallyhaving a remote server. To do so,simply


install the programs on the same machine,
all of
start rmiregistry, start
AddServer.,
and then execute AddClientusing this
command line:
java AddClient [Link] 8 9
Here,the address [Link] is the"loopback" addressfor the local machinc. Using
this addressallowsyou to exercise the entire
RMI mechanism without actually
to having
install the server on a remote computer.

Sample output from this program is shown here:


The first number is: 8
The second number is: 9

The sum is: 17.0

25 |ae

You might also like