UNIT-2
2.1 RMI (REMOTE METHOD INVOCATION)
2.2 DISTRIBUTED APPLICATION ARCHITECTURE
2.3 DEFINING REMOTE OBJECTS
2.4 REMOTE OBJECT ACTIVATION
2.5 SERIALIZATION AND DESERIALIZATION IN JAVA
2.1 RMI (Remote Method Invocation)
Remote Method Invocation (RMI) is an API that allows an object to invoke a method on
an object that exists in another address space, which could be on the same machine or
on a remote machine. Through RMI, an object running in a JVM present on a computer
(Client-side) can invoke methods on an object present in another JVM (Server-side). RMI
creates a public remote server object that enables client and server-side
communications through simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and sends
this information to the server.
The block consists of
● An identifier of the remote object to be used
● Method name which is to be invoked
● Parameters to the remote JVM
Skeleton Object: The skeleton object passes the request from the stub object to the
remote object. It performs the following tasks
● It calls the desired method on the real object present on the server.
● It forwards the parameters received from the stub object to the method.
Working of RMI
The communication between client and server is handled by using two intermediate
objects: Stub object (on client side) and Skeleton object (on server-side) as also can be
depicted from below media as follows:
These are the steps to be followed sequentially to implement Interface as defined below
as follows:
1. Defining a remote interface
2. Implementing the remote interface
29
3. Creating Stub and Skeleton objects from the implementation class using rmic
(RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
Step 1: Defining the remote interface
The first thing to do is to create an interface that will provide the description of the
methods that can be invoked by remote clients. This interface should extend the Remote
interface and the method prototype within the interface should throw the
RemoteException.
Example:
// Creating a Search interface
import [Link].*;
public interface Search extends Remote
{
// Declaring the method prototype
public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote interface,
the class should extend to UnicastRemoteObject class of [Link] package. Also, a default
constructor needs to be created to throw the [Link] from its parent
constructor in class.
// Java program to implement the Search interface
import [Link].*;
import [Link].*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
}
30
// Implementation of the query interface
public String query(String search)
throws RemoteException
{
String result;
if ([Link]("Reflection in Java"))
result = "Found";
else
result = "Not Found";
return result;
}
}
Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton
objects. Its prototype is rmic classname. For above program the following command
need to be executed at the command prompt
rmic SearchQuery.
Step 4: Start the rmiregistry
Start the registry service by issuing the following command at the command prompt start
rmiregistry
Step 5: Create and execute the server application program
The next step is to create the server application program and execute it on a separate
command prompt.
The server program uses createRegistry method of LocateRegistry class to create
rmiregistry within the server JVM with the port number passed as an argument.
The rebind method of Naming class is used to bind the remote object to the new name.
// Java program for server application
import [Link].*;
import [Link].*;
public class SearchServer
{
public static void main(String args[])
{
try
{
31
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();
// rmiregistry within the server JVM with
// port number 1900
[Link](1900);
// Binds the remote object by the name
// geeksforgeeks
[Link]("rmi://localhost:1900"+
"/geeksforgeeks",obj);
}
catch(Exception ae)
{
[Link](ae);
}
}
}
Step 6: Create and execute the client application program
The last step is to create the client application program and execute it on a separate
command prompt . The lookup method of the Naming class is used to get the reference
of the Stub object.
// Java program for client application
import [Link].*;
public class ClientRequest
{
public static void main(String args[])
{
String answer,value="Reflection in Java";
try
{
// lookup method to find reference of remote object
Search access =
(Search)[Link]("rmi://localhost:1900"+
"/geeksforgeeks");
32
answer = [Link](value);
[Link]("Article on " + value +
" " + answer+" at GeeksforGeeks");
}
catch(Exception ae)
{
[Link](ae);
}
}
}
The above client and server program is executed on the same machine so localhost is
used. In order to access the remote object from another machine, localhost is to be
replaced with the IP address where the remote object is present.
Save the files respectively as per class name as [Link] , [Link] ,
[Link] & [Link]
RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the
distributed applications in java.
Stub and Skeleton objects are used for communication between the client and server-
side.
_____________________________________________________________________
2.2 DISTRIBUTED APPLICATION ARCHITECTURE
Architecture styles in distributed systems define how components interact and are
structured to achieve scalability, reliability, and efficiency.
What are Distributed Systems?
Distributed Systems are networks of independent computers that work together to
present themselves as a unified system. These systems share resources and coordinate
tasks across multiple nodes, allowing them to work collectively to achieve common
goals.
Architecture Styles in Distributed Systems
To show different arrangement styles among computers, Architecture styles are
proposed.
1. Layered Architecture in Distributed Systems
● Layered Architecture in distributed systems organizes the system into
hierarchical layers, each with specific functions and responsibilities.
33
● This design pattern helps manage complexity and promotes separation of
concerns.
● This separation helps in managing and scaling the system more effectively.
Examples of Layered Architecture in Distributed System
Web Applications: A common example includes web applications with a presentation
layer (user interface), application layer (business logic), and data access layer (database
interactions).
Enterprise Systems: Large enterprise systems often use layered architecture to separate
user interfaces, business logic, and data management.
2. Peer-to-Peer (P2P) Architecture in Distributed Systems
● Peer-to-Peer (P2P) Architecture is a decentralized network design where each
node, or “peer,” acts as both a client and a server.
● In a P2P architecture, all nodes (peers) are equal participants in the network, each
capable of initiating and receiving requests.
● Peers collaborate to share resources, such as files or computational power,
without relying on a central server.
Examples of Peer-to-Peer (P2P) Architecture in Distributed Systems
File Sharing Networks: Systems like BitTorrent allow users to share and download files
from multiple peers, with each peer contributing to the upload and download processes.
Decentralized Applications (DApps): Applications that run on decentralized networks,
leveraging P2P architecture for tasks like data storage and computation.
3. Data-Centric Architecture in Distributed Systems
● Data-Centric Architecture is an architectural style that focuses on the central
management and utilization of data.
● In this approach, data is treated as a critical asset, and the system is designed
around data management, storage, and retrieval processes.
● This system is used to support efficient data management and manipulation.
Examples of Data-Centric Architecture in Distributed Systems
Relational Databases: Systems like MySQL, PostgreSQL, and Oracle use Data-Centric
Architecture to manage and store structured data efficiently, providing consistent access
and integration across applications.
Data Warehouses: Platforms such as Amazon Redshift and Google BigQuery are
designed to centralize and analyze large volumes of data from various sources, enabling
complex queries and data analysis.
4. Service-Oriented Architecture (SOA) in Distributed Systems
34
● Service-Oriented Architecture (SOA) is a design paradigm in distributed systems
where software components, known as “services,” are provided and consumed
across a network.
● Each service is a discrete unit that performs a specific business function and
communicates with other services through standardized protocols.
Examples of Service-Oriented Architecture (SOA) in Distributed Systems
Enterprise Systems: SOA is commonly used to integrate various enterprise applications
such as ERP, CRM, and HR systems, allowing them to work together seamlessly.
Web Services: Many modern web applications leverage SOA principles to interact with
external services via APIs, enabling functionalities such as payment processing, data
retrieval, and authentication.
5. Event-Based Architecture in Distributed Systems
● Event-Driven Architecture (EDA) is an architectural pattern where the flow of
data and control in a system is driven by events.
● Components in an EDA system communicate by producing and consuming
events, which represent state changes or actions within the system.
Examples of Event-Based Architecture in Distributed Systems
Real-Time Analytics: Systems like stock trading platforms use EDA to process and
respond to market events in real time.
IoT Systems: Internet of Things (IoT) applications use EDA to manage and respond to
data from various sensors and devices.
Fraud Detection: Financial institutions use EDA to detect and respond to suspicious
activities or anomalies in real time.
6. Microservices Architecture for Distributed Systems
● Microservices Architecture is a design pattern where an application is composed
of small, independent services that each perform a specific function.
● These services are loosely coupled and interact with each other through
lightweight communication protocols, often over HTTP or messaging queues.
Examples of Microservices Architecture for Distributed Systems
E-Commerce Platforms: Platforms like Amazon use microservices to handle different
aspects of their operations, such as user authentication, payment processing, and order
management.
Financial Services: Banks and financial institutions use microservices to manage various
functions, including transaction processing, customer management, and compliance.
35
7. Client Server Architecture in Distributed Systems
● Client-Server Architecture is a foundational model in distributed systems where
the system is divided into two main components: clients and servers.
● In Client-Server Architecture, clients request services or resources, while servers
provide those services or resources.
● The client initiates a request to the server, which processes the request and
returns the appropriate response.
Examples of Client Server Architecture in Distributed Systems
Web Applications: In a typical web application, web browsers (clients) request web
pages or data from web servers.
Email Systems: Email clients connect to email servers to send, receive, and manage email
messages.
_____________________________________________________________________
2.3 DEFINING REMOTE OBJECTS
Introduction to RMI
● Remote Method Invocation (RMI) is a Java API that allows invoking methods on
an object located in a different Java Virtual Machine (JVM).
● It enables seamless communication between distributed applications.
● Key features:
○ Location Transparency: Clients interact with remote objects as if they
are local.
○ Object Serialization: Transfers objects over the network.
○ Security: RMI uses Java's security manager for access control.
Key Components of RMI
1. Remote Interface: Declares the methods that can be called remotely.
2. Remote Object: Implements the remote interface.
3. RMI Registry: Acts as a naming service for binding and looking up remote
objects.
4. Stub and Skeleton:
○ Stub: Proxy on the client-side.
○ Skeleton (pre-Java 5): Dispatches calls on the server-side (replaced by
reflection in newer versions).
Steps to Define a Remote RMI Object
Step 1: Define the Remote Interface
● A remote interface extends the [Link] interface.
36
● All methods must throw [Link].
import [Link];
import [Link];
public interface Calculator extends Remote {
// Method to add two numbers
int add(int a, int b) throws RemoteException;
// Method to subtract two numbers
int subtract(int a, int b) throws RemoteException;
}
Step 2: Implement the Remote Interface
● The implementation class must extend [Link].
● Implement all methods defined in the remote interface.
import [Link];
import [Link];
public class CalculatorImpl extends UnicastRemoteObject implements
Calculator {
// Constructor
protected CalculatorImpl() throws RemoteException {
super();
}
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}
}
Step 3: Create and Register the Remote Object
● Use the [Link] class to create and bind the object to
the RMI Registry.
import [Link];
import [Link];
public class Server {
37
public static void main(String[] args) {
try {
// Create remote object
Calculator calculator = new CalculatorImpl();
// Bind the remote object to the RMI registry
Registry registry = [Link](1099);
[Link]("CalculatorService", calculator);
[Link]("Server is ready.");
} catch (Exception e) {
[Link]();
}
}
}
Testing the RMI Object
Client Code
● Lookup the remote object in the RMI registry and invoke its methods.
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
try {
// Lookup the registry for the remote object
Registry registry = [Link]("localhost", 1099);
Calculator calculator = (Calculator) [Link]("CalculatorService");
// Invoke methods on the remote object
[Link]("Addition:"+ [Link](10, 5));
[Link]("Subtraction:"+ [Link](10, 5));
} catch (Exception e) {
[Link]();
}
}
}
Compiling and Running RMI Applications
1. Compile Classes: Use javac to compile all classes.
38
2. Generate Stubs (Pre-Java 5): Use the rmic tool to generate stub classes.
3. Start RMI Registry: Run rmiregistry from the command line.
4. Run Server: Start the server application.
5. Run Client: Execute the client application.
Advantages of RMI
● Easy to use and integrates seamlessly with Java.
● Abstracts underlying complexities of network communication.
● Supports object-oriented distributed programming.
_____________________________________________________________________
2.4 REMOTE OBJECT ACTIVATION
Introduction
● Remote Object Activation is a feature in Java's RMI that enables creating
remote objects on demand.
● It allows an object to be activated only when a client requests it, reducing
resource usage compared to keeping objects always in memory.
● Activation provides scalability by managing object lifecycle dynamically.
Key Concepts
1. Persistent Naming:
○ Activated objects are registered with a persistent naming service to
enable lookup even after they are deactivated.
2. Object State:
○ Objects retain their state across activations, allowing seamless
interaction for clients.
3. Activation Daemon:
○ The rmid daemon manages the activation of objects when they are
needed.
Components of Remote Object Activation
1. Activation Group:
○ A container for activated objects.
○ Manages the shared resources for objects in the same group.
○ Implements [Link].
2. Activation Descriptor:
○ Provides the information needed to activate an object, such as its class
name, location, and initialization parameters.
○ Implements [Link].
39
3. Activation System:
○ A central registry to manage activation groups and descriptors.
○ Implemented by the [Link] interface.
Steps to Implement Remote Object Activation
Step 1: Define the Remote Interface
● Similar to a regular RMI object, the remote interface defines the methods
accessible to clients.
import [Link];
import [Link];
public interface MyService extends Remote {
String getMessage() throws RemoteException;
}
Step 2: Implement the Remote Object
● The implementation class extends Activatable instead of UnicastRemoteObject.
● Use a constructor that accepts ActivationID and MarshalledObject.
import [Link];
import [Link];
import [Link];
import [Link];
public class MyServiceImpl extends Activatable implements MyService {
public MyServiceImpl(ActivationID id, MarshalledObject<?> data)
throws RemoteException {
super(id, 0); // Call to superclass constructor
}
@Override
public String getMessage() throws RemoteException {
return "Hello, activated world!";
}
}
Step 3: Create an Activation Group
● Activation groups are required to manage the lifecycle of activated objects.
● Set up a group descriptor and register it.
import [Link].*;
public class ActivationSetup {
public static void main(String[] args) {
40
try {
ActivationGroupDesc groupDesc = new ActivationGroupDesc(null, null);
ActivationGroupID groupID =
[Link]().registerGroup(groupDesc);
ActivationDesc objectDesc = new ActivationDesc(
groupID,
"MyServiceImpl",
"[Link]
null
);
MyService stub = (MyService) [Link](objectDesc);
[Link]("Stub registered: " + stub);
} catch (Exception e) {
[Link]();
}
}
}
Step 4: Start the Activation System
Run the rmid activation daemon:
bash
rmid -[Link]=policyfile
Start the RMI registry:
bash
rmiregistry
Start the server application.
Step 5: Client Code
The client looks up the remote object as usual and invokes methods on it.
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
try {
Registry registry = [Link]("localhost");
MyService service = (MyService) [Link]("MyService");
[Link]([Link]());
41
} catch (Exception e) {
[Link]();
}
}
}
Advantages of Activation
● Resource Efficiency: Objects are created only when needed, conserving
memory and processing power.
● Scalability: Simplifies the development of large-scale distributed systems by
dynamically managing remote objects.
● Fault Tolerance: Allows recovery and reactivation of objects in case of server
failures.
_____________________________________________________________________
2.5 SERIALIZATION AND DESERIALIZATION IN JAVA
Introduction
● Serialization: The process of converting an object into a byte stream to store it
in a file, database, or transmit it over a network.
● Deserialization: The process of reconstructing the object from the byte stream.
Key Features
● Provides persistence for objects.
● Facilitates communication between systems by transferring objects as byte
streams.
● Ensures state consistency when objects are passed between applications.
Classes and Interfaces for Serialization
● [Link]:
○ A marker interface (does not contain methods).
○ Any class implementing this interface is eligible for serialization.
● ObjectOutputStream:
○ Used to write objects to an output stream.
● ObjectInputStream:
○ Used to read objects from an input stream.
Serialization Example
Step 1: Define a Serializable Class
● Implement Serializable in the class.
● All fields of the class should be serializable (primitives and serializable objects).
42
import [Link];
public class Employee implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for
version control
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
[Link] = name;
[Link] = id;
[Link] = salary;
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", salary=" +
salary + "}";
}
}
Step 2: Serialize the Object
● Use ObjectOutputStream to write the object to a file.
import [Link];
import [Link];
public class SerializeDemo {
public static void main(String[] args) {
Employee emp = new Employee("John Doe", 101, 50000.0);
try (FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
[Link](emp); // Serialize the object
[Link]("Object has been serialized.");
}
catch (Exception e) {
[Link]();
}
}
}
43