[go: up one dir, main page]

0% found this document useful (0 votes)
555 views23 pages

Unit 4 RMI Some Questions and Answers

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)
555 views23 pages

Unit 4 RMI Some Questions and Answers

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/ 23

Unit 4 12M

Java Remote Method Invocation:


Understanding Remote Method Invocation (RMI), Client /Server architecture, Implementing
RMI, Limitations of RMI Pass by value Vs Pass by reference.
RMI Architecture: RMI and Interface versus implementation, Stubs and skeletons, Bootstrapping
and the RMI registry, RMI URL, Exporting remote object.

1
Define Remote Method Invocation? Draw the neat, labeled diagram RMI Architecture and
list its components

➔ RMI:

❖ RMI stands for Remote Method Invocation.

❖ RMI is an API that provides a mechanism to create distributed applications 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.

❖ It is a mechanism that allows an object residing in one system (JVM) to access an object
running on another JVM.

❖ RMI is used to build distributed applications; it provides remote communication between


Java programs. It is provided in the package java.rmi.

➔ Architecture of an RMI Application:

➔ https://www.tutorialspoint.com/java_rmi/java_rmi_introduction.htm

Let us now discuss the components of this architecture.

 Transport Layer

 Stub

 Skeleton

 RRL (Remote Reference Layer)


2
3
State the tasks performed by Stub and Skeleton with neat diagram.

➔ 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 the parameters to (JVM)

3. It waits for the result

4. It reads the return value or exception, and

5. It finally returns the value to the caller.

❖ The role of the stubs is to marshal and unmarshal the messages that are sent and received
on the client or the server side

➔ 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 the result to the caller.

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

Server side stub is referred to as a skeleton.


4
Understanding requirements for the distributed
applications (https://www.javatpoint.com/RMI)
If any application performs these tasks, it can be distributed application.

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application has all these features, so it is called the distributed application.

5
Explain architecture of an RMI Application with neat diagram?

https://www.tutorialspoint.com/java_rmi/java_rmi_introduction.htm

➔ In an RMI application, we write two programs, a server program and a client program.

➔ The following diagram shows the architecture of an RMI application

● Components of this architecture.

● Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.

● 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.

6
Write down 6 steps to write the RMI program.
Ans
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 rmi registry tool
5. Create and start the remote application
6. Create and start the client application

Steps to develop a RMI Java application,

● Define interfaces and implementations of the component to be used from remote hosts.

● Compile the classes(using javac) and generate stub and skeleton(using rmic) of the
classes to be used from remote hosts

● Publish the service on the registry name service start the registry register the service(the
server must send a bind request to the registry)

● Obtain(client-side)the reference to the remote object sending a lookup request to the


registry After the last step,client and server can interact.

The Naming class provides methods to get and store the remote object. The Naming class provides 5
methods. (https://www.javatpoint.com/RMI)

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


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

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

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


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

public static void rebind(java.lang.String, java.rmi.Remote) throws It binds the remote object to

7
java.rmi.RemoteException, java.net.MalformedURLException; 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.

Explain RMI Registry with neat diagram?

➔ 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 RMI registry (using bind() or reBind()
methods). These are registered using a unique name known as bind name.

➔ To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name (using lookup() method).

The following illustration explains the entire process:

8
Explain the following terms

1) Goals of RMI
2)Remote Object

➔ 1) Following are the Goals of RMI −

❖ To minimize the complexity of the application.

❖ To preserve type safety.

❖ Distributed garbage collection.

❖ Minimize the difference between working with local and remote objects.

➔ 2) Remote Objects

❖ The RMI (Java Remote Method Invocation) system is a mechanism that enables an object
on one Java virtual machine to invoke methods on an object in another Java virtual
machine.

❖ Any object whose methods can be invoked in this way must implement the
java.rmi.Remote interface. When such an object is invoked, its arguments are marshalled
and sent from the local virtual machine to the remote one, where the arguments are
unmarshalled and used.

❖ When the method terminates, the results are marshalled from the remote machine and sent
to the caller's virtual machine.

❖ To make a remote object accessible to other virtual machines, a program typically registers
it with the RMI registry.

❖ The program supplies to the registry the string name of the remote object as well as the
remote object itself. When a program wants to access a remote object, it supplies the
object's string name to the registry that is on the same machine as the remote object. The
registry returns to the caller a reference (called stub) to the remote object. When the
program receives the stub for the remote object, it can invoke methods on the object
(through the stub).

9
Explain the following Parameter passing concept in RMI.

I).Primitive data types / Parameters.

II) Objects.

➔ Parameters in RMI

❖ RMI supports method calls to remote objects.

❖ When these calls involve passing parameters or accepting a return value, it


depends on whether the parameters are :

I. Primitive Parameters:

a) When a primitive data type is passed as a parameter to a remote method, the RMI system
passes it by value.

b) RMI will make a copy of a primitive data type and send it to the remote method. If a
method returns a primitive data type, it is also returned to the calling JVM by value.

c) Values are passed between JVMs in a standard, machine-independent format.

d) This allows JVMs running on different platforms to communicate with each other
reliably.

II. Object Parameters:

a) When an object is passed to a remote method, the semantics change from the case of the
single JVM.

b) RMI sends the object itself, not its reference, between JVMs.

c) It is the object that is passed by value, not the reference to the object.

d) Similarly, when a remote method returns an object, a copy of the whole object is returned
to the calling program.

e) Because different JVMs do not share heap memory, RMI must send the referenced object
and all objects it references.

10
Pass by Value vs. Pass by Reference

https://cseweb.ucsd.edu/classes/sp16/cse291-e/applications/ln/lecture3.html

In Java, parameters are passed into methods and returned from methods by reference. This is
problematic for an RMI facility, because not all objects can be remote objects - not all JVMs are
willing to expose any of their objects, never mind all of them. As a result, the RMI facility needs
to determine which object can be passed by reference, and which can't. And, it needs to have
some mechanism for handling those that can't be passed by reference.

To address the first concern, Java has a very simple rule. Any object that is to be remotely
accessible must be an instance of a class that implements the Remote interface. Objects that
implement the Remote interface are passed by reference into methods and when they are returned
from methods. Other objects are passed by value, in other words by creating local copies.

Java passes object by value using a process known as serialization. Basically, this means that
Java flattens out the object, copies it, and sends this copy to the other side. At the other side, the
object is recreated from the serialized copy, and a reference to this recreated object is used. Java
needs to have an object's .class file to reconstitute it from the serialized copy.

In order to recreate an object from a serialized copy, the object's .class file is needed. To facilitate
this, Java sends the URL for the .class file along with the serialized copy. If the recipient doesn't
already have the .class file, it can download it via HTTP using the provided URL.

The result of this process is that there are two copies - one on each side. The client's JVM has one
copy and the server's JVM has another. Each acts on its own copy. The object has been passed by
value.

When Java passes an object by reference, it does this by passing a remote reference to the object,
along with the URL of the stub class. This enables the recipient to recreate the stub object just as
it did objects passed by value. As before, if the recipient doesn't already have a copy of the
defining .class file, it can download it using HTTP via the provided URL.

The process of recreating a remote object or stub on the local system is called localization. Pass
by value localizes the remote object, pass by reference localizes a stub for the remote object.

11
State RMI URL and its format?

➔ RMI URLs
❖ JNDI (Java Naming and Directory Interface) provides support for resolving URLs that
name objects. The registry service provider allows RMI URLs to be used as names in this
manner. This provides a generalization of the java.rmi.Naming functionality, only using
the more general JNDI interface.

❖ The class com.sun.jndi.url.rmi.rmiURLContextFactory implements a URL context factory


for RMI URLs. This allows an RMI URL to be passed as a name to the default JNDI
initial context.

➔ RMI URL Format


❖ The format of an RMI URL is one of the following:

rmi://[host][:port][/[object]]

rmi:[/][object]

❖ If the object name is absent, then the URL names the registry at the given host and port.
Otherwise, it names the remote object registered at that registry under the name provided.

❖ If the host is omitted, the local host is assumed. If the port is omitted, the default registry
port 1099 is assumed.

Package java.rmi.registry
https://docs.oracle.com/en/java/javase/14/docs/api/java.rmi/java/rmi/registry/package-
summary.html

Provides a class and two interfaces for the RMI registry. A registry is a remote object that maps
names to remote objects. A server registers its remote objects with the registry so that they can be
looked up. When an object wants to invoke a method on a remote object, it must first lookup the
remote object using its name. The registry returns to the calling object a reference to the remote
object, using which a remote method can be invoked.

Since:

Interface Summary
Interface Description
Registry Registry is a remote interface to a simple remote object registry that

12
provides methods for storing and retrieving remote object references
bound with arbitrary string names.
RegistryHandler Deprecated.
no replacement

Class Summary
Class Description
LocateRegistry LocateRegistry is used to obtain a reference to a bootstrap remote object
registry on a particular host (including the local host), or to create a remote
object registry that accepts calls on a specific port.

https://www.tutorialspoint.com/java_rmi/java_rmi_database_application.htm
https://docs.oracle.com/javase/jndi/tutorial/provider/url/factory.html

Class UnicastRemoteObject
https://docs.oracle.com/javase/8/docs/api/java/rmi/server/UnicastRemoteObject.html

Class UnicastRemoteObject

 java.lang.Object
 java.rmi.server.RemoteObject
 java.rmi.server.RemoteServer
 java.rmi.server.UnicastRemoteObject

public class UnicastRemoteObjectextends RemoteServer


Used for exporting a remote object with JRMP and obtaining a stub that communicates to the
remote object. Stubs are either generated at runtime using dynamic proxy objects, or they are
generated statically at build time, typically using the rmic tool.

https://www.javatpoint.com/RMI

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
13
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 needs only two files, remote interface and client
application. In the rmi application, both client and server interact 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;
14
}

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.

15
public static java.rmi.Remote It returns the reference of the
lookup(java.lang.String) throws remote object.
java.rmi.NotBoundException,
java.net.MalformedURLException,
java.rmi.RemoteException;

public static void bind(java.lang.String, It binds the remote object with


java.rmi.Remote) throws the given name.
java.rmi.AlreadyBoundException,
java.net.MalformedURLException,
java.rmi.RemoteException;

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


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

public static void rebind(java.lang.String, It binds the remote object to the


java.rmi.Remote) throws new name.
java.rmi.RemoteException,
java.net.MalformedURLException;

public static java.lang.String[] It returns an array of the names


list(java.lang.String) throws of the remote objects bound in
java.rmi.RemoteException, the registry.
java.net.MalformedURLException;

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);}
}
16
}

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.

AD

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


17
rmiregistry 5000

4) start the server in another command prompt

java MyServer

5) start the client application in another command prompt

java MyClient

18
Output of this RMI example

19
Meaningful example of RMI application with database

Consider a scenario, there are two applications running in different machines. Let's
say MachineA and MachineB, machineA is located in United States and MachineB
in India. MachineB want to get list of all the customers of MachineA application.

Let's develop the RMI application by following the steps.

1) Create the table

First of all, we need to create the table in the database. Here, we are using Oracle10
database.

2) Create Customer class and Remote interface


File: Customer.java

package com.javatpoint;
public class Customer implements java.io.Serializable{
private int acc_no;
private String firstname,lastname,email;
private float amount;
//getters and setters
}

Note: Customer class must be Serializable.


File: Bank.java

package com.javatpoint;
20
import java.rmi.*;
import java.util.*;
interface Bank extends Remote{
public List<Customer> getCustomers()throws RemoteException;
}

3) Create the class that provides the implementation of Remote interface


File: BankImpl.java

package com.javatpoint;
import java.rmi.*;
import java.rmi.server.*;
import java.sql.*;
import java.util.*;
class BankImpl extends UnicastRemoteObject implements Bank{
BankImpl()throws RemoteException{}

public List<Customer> getCustomers(){


List<Customer> list=new ArrayList<Customer>();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from customer400");
ResultSet rs=ps.executeQuery();

while(rs.next()){
Customer c=new Customer();
c.setAcc_no(rs.getInt(1));
c.setFirstname(rs.getString(2));
c.setLastname(rs.getString(3));
c.setEmail(rs.getString(4));
c.setAmount(rs.getFloat(5));
list.add(c);
}

con.close();
}catch(Exception e){System.out.println(e);}
return list;
21
}//end of getCustomers()
}

4) Compile the class rmic tool and start the registry service by rmiregistry tool

5) Create and run the Server


File: MyServer.java

package com.javatpoint;
import java.rmi.*;
public class MyServer{
public static void main(String args[])throws Exception{
Remote r=new BankImpl();
Naming.rebind("rmi://localhost:6666/javatpoint",r);
}}

22
6) Create and run the Client
File: MyClient.java

package com.javatpoint;
import java.util.*;
import java.rmi.*;
public class MyClient{
public static void main(String args[])throws Exception{
Bank b=(Bank)Naming.lookup("rmi://localhost:6666/javatpoint");

List<Customer> list=b.getCustomers();
for(Customer c:list){
System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()
+" "+c.getEmail()+" "+c.getAmount());
}

}}

23

You might also like