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

Java RMI: Foundations of Distributed Systems

Uploaded by

23130111
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 views83 pages

Java RMI: Foundations of Distributed Systems

Uploaded by

23130111
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

Java RMI

(Remote Method Invocation)


Java RMI

Part 1: Foundations of
Distributed Programming
The Rise of Distributed Computing
◼ Centralized Computing: Early computing was
performed on a single processor, also known as
centralized computing. This approach has
limitations in terms of resource pooling, reliability,
and scalability.
◼ Distributed System: A collection of independent
computers interconnected via a network, capable
of collaborating on a task.
◼ Distributed Computing: The act of computing
performed in a distributed system, leveraging
resources from multiple machines to solve a
problem.
Khoa CNTT – ĐH Nông Lâm TP. HCM 3/83
Centralized vs. Distributed Computing

terminal
mainframe computer
workstation

network link

network host
centralized computing
distributed computing

Khoa CNTT – ĐH Nông Lâm TP. HCM 4/83


Distributed Systems

work
stations a local network

The Internet

a network host

Khoa CNTT – ĐH Nông Lâm TP. HCM 5/83


Advantages of Distributed Computing
◼ Economics: Distributed systems allow for pooling of
resources, including CPU cycles, data storage, and I/O
devices, making them more cost-effective.
◼ Reliability & Fault Tolerance: By replicating
resources and services across multiple machines, a
distributed system can reduce service outages in the
event of failures.
◼ Scalability: It is easier to expand a distributed
system by adding more nodes to handle increased
demand.
◼ Resource Sharing: Provides universal access to
resources and services across a network, which is the
foundation of the modern internet
Khoa CNTT – ĐH Nông Lâm TP. HCM 6/83
Disadvantages of distributed computing

◼ Multiple Points of Failure: The failure of a single


computer or network link can disrupt the entire
system.
◼ ecurity Concerns: More endpoints mean a larger
attack surface.

Khoa CNTT – ĐH Nông Lâm TP. HCM 7/83


Examples of Distributed systems
◼ The Internet
◼ An intranet: a network of computers and
workstations within an organization, segregated
from the Internet via a protective device (a
firewall).
◼ Network of workstations (NOW): a group of
networked personal workstations connected to
one or more server machines.
◼ The Search for ExtraTerrestrial Intelligence
(SETI) project

Khoa CNTT – ĐH Nông Lâm TP. HCM 8/83


Related Technologies
◼ RPC (Remote Procedure Calls): A protocol that
allows a program to request a service from a program
located on another computer. It was platform-specific
◼ CORBA (Common Object Request Broker
Architecture): A standard that allows access to non-
Java objects as well as Java objects, providing
platform interoperability
◼ DCOM (Distributed Component Object Model):
Developed by Microsoft to allow communication
between software components on networked
computers, primarily for the Windows platform
◼ LDAP (“Lightweight Directory Access Protocol”)
◼ Finding resources on a network

Khoa CNTT – ĐH Nông Lâm TP. HCM 9/83


Java RMI

Part 2: Introducing Java RMI


Java RMI: An Overview
◼ Definition: Remote Method Invocation (RMI)
is a distributed systems technology that allows
one Java Virtual Machine (JVM) to invoke
object methods that are running on another
JVM located elsewhere on a network.
◼ Core Principle: It allows objects to call
methods on other objects located remotely as
easily as if they were on the local host
machine. This is the concept of transparency

Khoa CNTT – ĐH Nông Lâm TP. HCM 11/83


Key Characteristics:
◼ Access to Remote Objects
◼ Java-to-Java Only: RMI is a pure Java

technologyClient-Server Protocol
◼ High-level API: It abstracts away low-level network
programming details
◼ Client-Server Protocol: It operates based on a

client-server communication model


◼ Transparent and Lightweight

Each RMI service is defined by an interface, which


describes object methods that can be executed
remotely. This interface must be shared by all
developers who will write software for that service - it
acts as a blueprint for applications that will use and
provide implementations
Khoa CNTT – of
ĐH the
Nông service.
Lâm TP. HCM 12/83
Remote Objects (Diagram)

Java Virtual Machine Java Virtual Machine

Client Remote
Object TCP Object

Khoa CNTT – ĐH Nông Lâm TP. HCM 13/83


Remote method invocation

Invocation of a method on a remote


object, executing on a remote
machine

Khoa CNTT – ĐH Nông Lâm TP. HCM 14/83


Local object – Remote object

Invocations on remote objects appear the same


as invocations on local objects.
Khoa CNTT – ĐH Nông Lâm TP. HCM 15/83
RMI Architecture: The Big Picture
◼ Client: The application that wants to invoke a remote
method
◼ Server: The application that hosts the remote object
and executes the remote method
◼ Stub: A proxy object that resides on the client side.
It implements the same remote interface as the
remote object and acts as a gateway for the client
◼ Skeleton: An object that resides on the server side.
It receives requests from the stub, unmarshals the
parameters, and invokes the correct method on the
actual remote object

Khoa CNTT – ĐH Nông Lâm TP. HCM 16/83


RMI Architecture

Khoa CNTT – ĐH Nông Lâm TP. HCM 17/83


RMI Architecture - Layers

Java Virtual Machine Java Virtual Machine


Client Remote
Object Object

Stub Skeleton

Remote Reference Layer Remote Reference Layer


TCP
Transport Layer Transport Layer

Khoa CNTT – ĐH Nông Lâm TP. HCM 18/83


RMI Architecture - Layers
◼ Stub − A stub is a representation (proxy) of the
remote object at client. It resides in the client system;
it acts as a gateway for the client program.
◼ Skeleton − This is the object which resides on the
server side. stub communicates with this skeleton to
pass request to the remote object.
◼ RRL(Remote Reference Layer) − It is the layer
which manages the references made by the client to
the remote object.
◼ Transport Layer − This layer connects the client and
the server. It manages the existing connection and
also sets up new connections.

Khoa CNTT – ĐH Nông Lâm TP. HCM 19/83


The Roles of Stub and Skeleton
◼ Stub
◼ lives on client

◼ pretends to be remote object

◼ Marshals (packs) parameters for the remote

call
◼ Sends the marshaled call to the server

◼ Receives the return value or exception from

the server

Khoa CNTT – ĐH Nông Lâm TP. HCM 20/83


The Roles of Stub and Skeleton
◼ Skeleton
◼ Lives on server

◼ Receives the call request from the stub

◼ Unmarshals (unpacks) the parameters

◼ Invokes the method on the true remote

object
◼ Marshals the return value or exception and

sends it back to the stub

Khoa CNTT – ĐH Nông Lâm TP. HCM 21/83


Parameter marshalling

Parameter Parameter
CLIENT SERVER
Parameter Parameter Remote
Remote Stub Skeleton Method
Method Invocation
Call Return value Return value
Exception Exception

Khoa CNTT – ĐH Nông Lâm TP. HCM 22/83


Java RMI

Part 3: The RMI Registry and


Application Flow
The RMI Registry
◼ Purpose: The RMI Registry is a simple, server-side
naming service that allows clients to look up a remote
object by a given name
◼ Server Interaction: A server creates its remote
object and then registers it with the registry using a
unique name (e.g., [Link]("Fred", myObject))
◼ Client Interaction: A client looks up the remote
object in the registry by its name (e.g.,
[Link]("Fred")) to obtain a remote reference
(the stub)
◼ Analogy: The RMI Registry acts like a "phone book"
or "yellow pages" for remote objects

Khoa CNTT – ĐH Nông Lâm TP. HCM 24/83


The RMI Registry

Khoa CNTT – ĐH Nông Lâm TP. HCM 25/83


Remote References and Interfaces
◼ Remote References
◼ Refer to remote objects

◼ Invoked on client exactly like local object

references
◼ Remote Interfaces
◼ Declare exposed methods

◼ Implemented on client

◼ Like a proxy for the remote object

Khoa CNTT – ĐH Nông Lâm TP. HCM 26/83


Remote Interfaces and Stubs

Remote Interface

implements implements

Remote Object
Client Stub Skeleton
(Server)

Khoa CNTT – ĐH Nông Lâm TP. HCM 27/83


The RMI Lifecycle

1. The server creates the remote object and registers it with the
RMI Registry.
2. A client requests the remote object's reference from the
registry.
3. The registry returns the remote reference (the stub) to the
client.
4. The client invokes a method on the stub.
5. The stub marshals the call and sends it to the server's skeleton.
6. The skeleton unmarshals the call and invokes the actual
method on the remote object.
7. The remote object executes the method and returns the result
to the skeleton.
8. The skeleton marshals the result and sends it back to the stub.
9. The stub unmarshals the result and returns it to the client

Khoa CNTT – ĐH Nông Lâm TP. HCM 28/83


The RMI Lifecycle

Client Virtual Machine Server Virtual Machine


Client Remote
Object

Stub Skeleton
Server

“Fred”

Registry Virtual Machine

Khoa CNTT – ĐH Nông Lâm TP. HCM 29/83


RMI Flow 1. Server Creates Remote Object
2. Server Registers Remote Object

Client Virtual Machine Server Virtual Machine


Client Remote
Object
1

Skeleton
Stub Server

“Fred”

Registry Virtual Machine


Khoa CNTT – ĐH Nông Lâm TP. HCM 30/83
RMI Flow 3. Client requests object from Registry
4. Registry returns remote reference
(and stub gets created)
Client Virtual Machine Server Virtual Machine
Client Remote
Object

Skeleton
Stub Server
3 4

“Fred”

Registry Virtual Machine


Khoa CNTT – ĐH Nông Lâm TP. HCM 31/83
RMI Flow 5. Client invokes stub method
6. Stub talks to skeleton
7. Skeleton invokes remote object
method

Client Virtual Machine Server Virtual Machine


Client Remote
Object
5 7

6
Skeleton
Stub Server

“Fred”

Registry Virtual Machine


Khoa CNTT – ĐH Nông Lâm TP. HCM 32/83
Java RMI

Part 4: Building a Simple RMI


Application
RMI Application Development Steps
◼ On the Server Side:
1) Define the Remote Interface
2) Develop the Implementation Class (the remote object)
3) Develop the Server Program to create and register the
object
◼ On the Client

◼ Develop the Client Program to look up and use the

remote object
◼ Compilation & Execution

1) Compile the Java classes using javac


2) Generate stubs and skeletons using rmic. (JDK 1.4 or
earlier)
3) Start the RMI Registry, the server, and then the client

Khoa CNTT – ĐH Nông Lâm TP. HCM 34/83


Defining the Remote Interface
◼ A remote interface provides the description of all the
methods of a particular remote object. The client
communicates with this remote interface.
1. Create an interface that extends [Link].
2. Declare all methods that can be invoked remotely.
3. Each method must throw [Link].

import [Link].*;
public interface IProduct extends Remote{
String getDescription() throws RemoteException;
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 35/83


Implement the Remote Interface
◼ Create a class that implements the remote interface
◼ This class must extend
[Link]
import …;
public class ProductImpl extends
UnicastRemoteObject implements IProduct{
private String name;
protected ProductImpl(String name) throws
RemoteException {
super();
[Link] = name;
}
public String getDescription() {
return "I am a " + name + ". Buy me!";
}
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 36/83
Compiling Remote Classes
◼ Compile the Java class
◼ javac
◼ reads .java file

◼ produces .class file

◼ Compile the Stub and Skeleton


◼ rmic
◼ reads .class file

◼ produces _Skel.class and _Stub.class

Khoa CNTT – ĐH Nông Lâm TP. HCM 37/83


Naming conventions for RMI classes
◼ IProduct A remote interface
◼ ProductImpl A server class implementing
that interface
◼ ProductImpl_Stub A stub class that is
automatically generated by the rmic program
◼ ProductImpl_Skel A skeleton class that is
automatically generated by the rmic program
needed for SDK 1.1
◼ ProductServer A server program that creates
server objects
◼ ProductClient A client program that calls
remote methods

Khoa CNTT – ĐH Nông Lâm TP. HCM 38/83


Creating the RMI Server
1) Create a main method
2) Create an instance of the remote object
implementation class
3) Create and launch an RMI (Remote Method
Invocation) registry on the local host that accepts
requests on the specified port using
[Link]()
4) Binds a remote reference to the specified name in
this registry (register the object) using rebind()
method

Khoa CNTT – ĐH Nông Lâm TP. HCM 39/83


Creating the RMI Server
public class ProductServer {
public static void main(String[] args){
try {
IProduct product = new ProductImpl("Canon EOS
350D");
Registry registry =
[Link](1099);
[Link]("EOS350D", product);
[Link]("Server is running...");
} catch (Exception e) {
[Link]("Server exception: " +
[Link]());
[Link]();
}
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 40/83
Creating the RMI Client
1) Create a main method
2) Use the [Link]() method to
obtain a reference to a remote RMI (Remote
Method Invocation) registry
3) Use the lookup() with the same service name to get
a remote object reference (a stub)
4) Cast the returned Remote object to your remote
interface type
5) Invoke the remote methods on the object as if it
were local

Khoa CNTT – ĐH Nông Lâm TP. HCM 41/83


Creating the RMI Client
public class ProductClient {
public static void main(String[] args){
try {
Registry registry =
[Link]("localhost", 1099);
IProduct product = (IProduct)
[Link]("EOS350D");
String description = [Link]();
[Link]("Product description: " +
description);
} catch (Exception e) {
[Link]("Client exception: " +
[Link]());
[Link]();
}
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 42/83
Calling the remote getDescription method

Khoa CNTT – ĐH Nông Lâm TP. HCM 43/83


Parameter Passing
◼ Primitive types
◼ passed by value

◼ Remote objects
◼ passed by reference

◼ Non-remote objects
◼ passed by value

◼ uses Java Object Serialization

◼ The object must implement the

[Link] marker interface

Khoa CNTT – ĐH Nông Lâm TP. HCM 44/83


Java Serialization
◼ Writes object as a sequence of bytes
◼ Writes it to a Stream
◼ Recreates it on the other end
◼ Creates a brand new object with the old data
◼ The serialVersionUID is a universal version
identifier for a Serializable class. Deserialization
uses this number to ensure that a loaded class
corresponds exactly to a serialized object. If no
match is found, then an InvalidClassException
is thrown

Khoa CNTT – ĐH Nông Lâm TP. HCM 45/83


Not All Objects Are Serializable

◼ Any object that doesn’t implement Serializable


◼ Any object that would pose a security risk
◼ e.g. FileInputStream
◼ Any object whose value depends on VM-specific
information
◼ e.g. Thread
◼ Any object that contains a (non-static, non-transient)
unserializable object (recursively)

Khoa CNTT – ĐH Nông Lâm TP. HCM 46/83


Java RMI

Part 5: RMI Disadvantages


and Advanced Solutions
RMI: The Hidden Challenges
◼ Tight Coupling with Java: RMI is a pure Java-to-
Java solution
◼ Network Latency: Every remote method call is a
network operation, which is significantly slower than a
local method call
◼ Single Point of Failure: By default, an RMI client
connects to a single remote object on a single
server. If that server or object fails, the entire client
application can crash
◼ Security Concerns: RMI relies on Java Serialization,
which can introduce security vulnerabilities

Khoa CNTT – ĐH Nông Lâm TP. HCM 48/83


The Single Remote Object Problem
◼ The Problem: In a typical RMI setup, the server
instantiates a single remote object and binds it to the
registry. All clients then connect to this single
instance
◼ Issues Arising from This:
◼ Synchronization Issues: When multiple clients
access the same remote object concurrently, shared
state may cause race conditions, data inconsistency, or
deadlocks if synchronization is not properly handled
◼ Performance Bottleneck: A single instance can
become a performance bottleneck when many clients
are accessing it
◼ Lack of Scalability: You cannot scale horizontally by
adding more servers
Khoa CNTT – ĐH Nông Lâm TP. HCM 49/83
RMI Single Object Example
public interface ICounter extends Remote {
void increment() throws RemoteException;
void decrement() throws RemoteException;
int getCount() throws RemoteException;
}
public class CounterImpl extends UnicastRemoteObject
implements ICounter {
private int count = 0;
Random rand = new Random();
public void increment() throws RemoteException {
try {
[Link]([Link](500));
} catch (InterruptedException e) {}
count++;
}
. . . . . .
} Khoa CNTT – ĐH Nông Lâm TP. HCM 50/83
RMI Single Object Example
public class CounterServer {
public static void main(String[] args) throws … {
Registry reg = [Link](1099);
[Link]("COUNTER", new CounterImpl());
}}

public class CounterClient1 {


. . . . .
Registry reg = [Link]();
ICounter counter = (ICounter) [Link]("COUNTER");
for (int i = 0; i<20; i++) [Link]();
[Link]("Client 1: " + [Link]());
}

public class CounterClient2 {


. . . .
for (int i = 0; i<5; i++) [Link]();
[Link]("Client 2: " + [Link]());
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 51/83
Solution 1: Load Balancing
◼ Concept: Distribute client requests across a pool of
identical remote objects hosted on multiple
servers. This improves performance and provides fault
tolerance
◼ How it works:
◼ Create multiple replicas of the remote object
implementation class
◼ Run an RMI server on each machine
◼ The client uses a custom load-balancing stub or a
smart proxy to route calls to an available server
instance, often using algorithms like Round Robin

Khoa CNTT – ĐH Nông Lâm TP. HCM 52/83


Solution 2: The Factory Pattern
(Per-Client Object)
◼ Concept: You bind a remote factory object to the
RMI registry. A client first connects to this factory,
which then creates and returns a new, dedicated
remote object for that specific client
◼ How it works:

◼ The server binds a single instance of a remote factory


to the RMI registry
◼ A client looks up the factory
◼ The client calls a method on the factory
◼ The factory creates a new object instance and returns
its stub to the client
◼ Each client now has its own unique remote object
instance to interact with
Khoa CNTT – ĐH Nông Lâm TP. HCM 53/83
Solution 2: The Factory Pattern
(Per-Client Object)
◼ Advantages:

◼ State Separation: Each client maintains its own state,


as it interacts with a dedicated object instance
◼ Improved Concurrency: Multiple clients can operate
on their own objects simultaneously without blocking
each other
◼ Scalable Instantiation: The factory can implement
logic to manage object creation

Khoa CNTT – ĐH Nông Lâm TP. HCM 54/83


Factory Pattern Example
public interface ICounterService extends Remote{
ICounter createCounter() throws RemoteException;
}

public class CounterServiceImpl extends


UnicastRemoteObject implements ICounterService {
public ICounter createCounter() throws ... {
return new CounterImpl();
}
}

public class CounterServer {


public static void main(String[] args) throws ... {
Registry reg = [Link](1099);
[Link]("COUNTER_SERVICE", new
CounterServiceImpl());
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 55/83
Factory Pattern Example
public class CounterClient1 {
public static void main(String[] args) throws . . . {
Registry reg = [Link]();
ICounterService counterService = (ICounterService)
[Link]("COUNTER_SERVICE");
ICounter counter = [Link]();
for (int i = 0; i<20; i++) [Link]();
[Link]("Client 1: " +
[Link]());
}}

public class CounterClient2 {


. . .
ICounter counter = [Link]();
for (int i = 0; i<5; i++) [Link]();
[Link]("Client 2: " +
[Link]());
} Khoa CNTT – ĐH Nông Lâm TP. HCM 56/83
The Session Pattern
A Variant of the Factory Pattern
◼ Recap of the Factory Pattern: This solution uses a
single, stateless factory object to create and return a
new, dedicated stateful remote object for each client. This
helps prevent bottlenecks and maintains the independence
of each client
◼ Introducing the Session Pattern: The "Session
Pattern" is a specific and common application of the
Factory Pattern, designed to solve the problem of
managing a user's session or state
◼ The Main Goal: To provide a mechanism for a client to
"log in" and receive an exclusive, stateful remote object
that persists for the duration of the client's work session.
This is analogous to the concept of an HTTP Session in
web programming
Khoa CNTT – ĐH Nông Lâm TP. HCM 57/83
The Session Pattern
◼ How It Works:
◼ The client calls a login() method on the Factory
object (e.g., IBankService)
◼ The factory creates a stateful Session object (e.g.,
IBankAccount) and returns its stub to the client
◼ The client uses this stub to perform stateful operations
(e.g., adding items to a shopping cart)
◼ The client ends the session by calling logout() on the
session object to release resources on the server

Khoa CNTT – ĐH Nông Lâm TP. HCM 58/83


Solution 3: Object Pooling
◼ Concept: The server maintains a pool of reusable
objects. When a client makes a request, an object
from the pool is checked out, used, and then returned
to the pool
◼ How it works:
◼ The server creates a pool of remote object instances
◼ A custom Remote Factory object is registered with
the RMI registry
◼ Clients look up this factory and call a method like
getRemoteObject() to obtain an object from the pool

Khoa CNTT – ĐH Nông Lâm TP. HCM 59/83


Solution 3: Object Pooling
◼ Advantages:
◼ Reduces Overhead: Avoids the performance cost of
repeatedly creating and garbage-collecting remote
objects
◼ Resource Management: Limits the total number of
remote objects, preventing the server from being
overwhelmed

Khoa CNTT – ĐH Nông Lâm TP. HCM 60/83


Using Remote Method
Invocation to Implement
Callbacks

Self study
Java RMI Client Server Interaction
Server host
Client host

1
[Link] 2 RMI registry
HTTP host
3

SomeInterface_stub.class
SomeInterface_stub.class
4
X
SomeInterface_skel.class

[Link]

1. Client looks up the interface object in the RMIregistry on the server host.
2. The RMIRegistry returns a remote reference to the interface object.
3. If the interface object's stub is not on the client host and if it is so arranged by the
server, the stub is downloaded from an HTTP server.
4. Via the server stub, the client process interacts with the skeleton of the interface object
to access the methods in the server object.

Khoa CNTT – ĐH Nông Lâm TP. HCM 62/83


CodeBase

A codebase can be defined as a source, or a place, from


which to load classes into a virtual machine

Khoa CNTT – ĐH Nông Lâm TP. HCM 63/83


CodeBase
1. The remote object's codebase is specified by the remote
object's server by setting the [Link]
[Link] codebase set on the server VM is
annotated to the remote object reference in the Java
RMI registry.
2. The Java RMI client requests a reference to a named
remote object. The reference (the remote object's stub
instance) is what the client will use to make remote
method calls to the remote object.
3. The Java RMI registry returns a reference (the stub
instance) to the requested class. If the class definition
for the stub instance can be found locally in the client's
CLASSPATH , which is always searched before the
codebase, the client will load the class locally. However,
if the definition for the stub is not found in the client's
CLASSPATH, the client will attempt to retrieve the class
definition from the remote object's codebase.
Khoa CNTT – ĐH Nông Lâm TP. HCM 64/83
CodeBase
4. The client requests the class definition from the
codebase. The codebase the client uses is the URL
that was annotated to the stub instance when the
stub class was loaded by the registry.
5. The class definition for the stub (and any other
class(es) that it needs) is downloaded to the client.
6. Now the client has all the information that it needs to
invoke remote methods on the remote object. The
stub instance acts as a proxy to the remote object
that exists on the server;
◼ In addition to downloading stubs and their associated
classes to clients, the [Link]
property can be used to specify a location from which
any class, not only stubs, can be downloaded.

Khoa CNTT – ĐH Nông Lâm TP. HCM 65/83


CodeBase

Java RMI client making a remote method call

Khoa CNTT – ĐH Nông Lâm TP. HCM 66/83


CodeBase

Java RMI client making a remote method call, passing


an unknown subtype as a method parameter
Khoa CNTT – ĐH Nông Lâm TP. HCM 67/83
Preparing for Deployment
◼ Deploying an application that uses RMI can be tricky
because so many things can go wrong and the error
messages that you get when something does go wrong are
so poor. Separate the class files into three subdirectories:
◼ server
◼ download
◼ client
◼ The server directory contains all files that are needed to
run the server. You will later move these files to the
machine running the server process. In our example, the
server directory contains the following files:
◼ server/
[Link]
[Link]
[Link]
Khoa CNTT – ĐH Nông Lâm TP. HCM 68/83
Preparing for Deployment
◼ The client directory contains the files that are needed to
start the client
◼ client/
[Link]
[Link]
[Link]
◼ You will deploy these files on the client computer. Finally,
the download directory contains those class files needed by
the RMI registry, the client, and the server, as well as the
classes they depend on. In our example, the download
directory looks like this:
◼ download/
ProductImpl_Stub.class
java - [Link] = [Link]
download/ ProductServer &
Khoa CNTT – ĐH Nông Lâm TP. HCM 69/83
Using RMI to Implement Callbacks

Multiple listeners can register


with one or more event sources.
Khoa CNTT – ĐH Nông Lâm TP. HCM 70/83
Using RMI to Implement Callbacks

Callback notification of
event, for every
registered listener
Khoa CNTT – ĐH Nông Lâm TP. HCM 71/83
Callback Client-Server Interactions
Server host
Client host

1
[Link] 2 RMI registry

SomeInterface_stub.class

3,4
SomeInterface_skel.class
X

[Link]
CallbackInterface_skel.class
5
CallbackInterface_stub.class

1. Client looks up the interface object in the RMIregistry on the server host.
2. The RMIRegistry returns a remote reference to the interface object.
3. Via the server stub, the client process invokes a remote method to register itself for callback,
passing a remote reference to itself to the server. The server saves the reference in its callback list.
4. Via the server stub, the client process interacts with the skeleton of the interface object
to access the methods in the interface object.
5. When the anticipated event takes place, the server makes a callback to each registered
client via the callback interface stub on the server side and the callback interface skeleton on the
client side.

Khoa CNTT – ĐH Nông Lâm TP. HCM 72/83


Defining the Listener Interface
◼The listener interface defines a remote object with a single
method. This method should be invoked by an event source
whenever an event occurs, so as to act as notification that the
event occurred. The method signifies a change in
temperature, and allows the new temperature to be passed as
a parameter.
interface TemperatureListener extends
Remote {
public void temperatureChanged(double
temperature)
throws [Link];
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 73/83


Defining the Event Source Interface
◼The event source must allow a listener to be registered
and unregistered, and may optionally provide additional
methods. In this case, a method to request the
temperature on demand is offered.
interface TemperatureSensor extends
[Link]{
public double getTemperature()
throws [Link];
public void addTemperatureListener
(TemperatureListener listener )
throws [Link];
public void removeTemperatureListener
(TemperatureListener listener )
throws [Link];
} 74/83
Khoa CNTT – ĐH Nông Lâm TP. HCM
Implementing the Event Source Interface
◼ A TemperatureSensorServerImpl class is defined,
which acts as an RMI server.
◼ To notify registered listeners as a client (The server must
extend UnicastRemoteObject, to offer a service, and
implement the Temperature Sensor interface.
◼ To create an instance of the service and registering it with the
rmiregistry
◼ To launch a new thread, responsible for
updating the value of the temperature, based
on randomly generated numbers.
◼ As each change occurs, registered listeners are notified, by
reading from a list of listeners stored in a
[Link] object. This list is modified by the
remote
addTemperatureListener(TemperatureListener
) and
removeTemperatureListener(TemperatureListe
Khoa CNTT – ĐH Nông Lâm TP. HCM 75/83
Implementing the Event Source Interface
public class TemperatureSensorImpl extends UnicastRemoteObject
implements TemperatureSensor, Runnable {
private volatile double temp; private Vector list = new Vector();
public TemperatureSensorImpl() throws [Link] {
super();
temp = 98.0; // Assign a default setting for the temperature
}
public double getTemperature() throws [Link] {
return temp;
}
public void addTemperatureListener(TemperatureListener listener)
throws [Link] {
[Link]("adding listener -" + listener);
[Link](listener);
}
public void removeTemperatureListener(TemperatureListener listener)
throws [Link] {
[Link]("removing listener -" + listener);
[Link](listener);
}
Khoa CNTT – ĐH Nông Lâm TP. HCM 76/83
Implementing the Event Source Interface
public void run() {
Random r = new Random();
for (; ; ) {
try {
// Sleep for a random amount of time
int duration = [Link]() % 10000 + 2000;
// Check to see if negative, if so, reverse
if (duration < 0) duration = duration * -1;
[Link](duration);
} catch (InterruptedException ie) {}
// Get a number, to see if temp goes up or down
int num = [Link]();
if (num < 0) temp += 0.5; else temp -= 0.5;
notifyListeners(); // Notify registered listeners
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 77/83
Implementing the Event Source Interface
private void notifyListeners() {
// Notify every listener in the registered list
for (Enumeration e = [Link]();
[Link]();) {
TemperatureListener listener = (TemperatureListener)
[Link]();
// Notify, if possible a listener
try {
[Link](temp);
} catch (RemoteException re) {
[Link]("removing listener -" + listener);
// Remove the listener
[Link](listener);
}}
}}

Khoa CNTT – ĐH Nông Lâm TP. HCM 78/83


Implementing the Listener Interface
◼ The temperature monitor client must implement the
TemperatureListener interface, and register itself
with the remote temperature sensor service, by invoking the
[Link]
(Temperature Listener) method.
◼ By registering as a listener, the monitor client will be
notified of changes as they occur, using a remote callback.
The client waits patiently for any changes, and though it
does not ever remove itself as a listener, functionality to
achieve this is supplied by the

[Link]
ner(
TemperatureListener)
method. Khoa CNTT – ĐH Nông Lâm TP. HCM 79/83
Implementing the Listener Interface
import [Link].*;
import [Link].*;
public class TemperatureListenerImpl extends
UnicastRemoteObject implements TemperatureListener {
// Default constructor throws a RemoteException
public TemperatureListenerImpl() throws RemoteException {
super();
}

public void temperatureChanged(double temperature)


throws [Link] {
[Link]("Temperature change event : " +
temperature);
}
}

Khoa CNTT – ĐH Nông Lâm TP. HCM 80/83


TemperatureSensorServer
public class TemperatureSensorServer{
public static void main(String args[]) {
[Link]("Loading temperature service");
try {
// Load the service
TemperatureSensorImpl sensor = new TemperatureSensorImpl();
// Register with service so that clients can find us
String registry = "localhost";
String registration = "rmi://" + registry + "/TemperatureSensor";
[Link](registration, sensor);
// Create a thread, and pass the sensor server. This will activate the
//run() method, and trigger regular temperature changes.
Thread thread = new Thread(sensor);
[Link]();
} catch (RemoteException re) {
[Link]("Remote Error - " + re);
} catch (Exception e) {
[Link]("Error - " + e);
}
}}
Khoa CNTT – ĐH Nông Lâm TP. HCM 81/83
TemperatureMonitor
public static void main(String args[]) {
[Link]("Looking for temperature sensor");
try {
// Lookup the service in the registry, and obtain a remote service
String registry = "localhost";
String registration = "rmi://" + registry + "/TemperatureSensor";
Remote remoteService = [Link](registration);
// Cast to a TemperatureSensor interface
TemperatureSensor sensor = (TemperatureSensor) remoteService;
// Get and display current temperature
double reading = [Link]();
[Link]("Original temp : " + reading);
// Create a new monitor and register it as a listener with remote sensor
TemperatureListenerImpl monitor = new TemperatureListenerImpl();
[Link](monitor);
} catch (RemoteException re) {
[Link]("RMI Error - " + re);
} catch (Exception e) {
[Link]("Error - " + e);
}} Khoa CNTT – ĐH Nông Lâm TP. HCM 82/83
Configuring a RMID

Khoa CNTT – ĐH Nông Lâm TP. HCM 83/83

You might also like