0% found this document useful (0 votes)
30 views11 pages

Unit 2

2 unit of java

Uploaded by

bharathimsccs81
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)
30 views11 pages

Unit 2

2 unit of java

Uploaded by

bharathimsccs81
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/ 11

1

RMI (Remote Method Invocation)

The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
The RMI provides remote communication between the applications using two
objects stub and skeleton.

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
6.
skeleton

The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does the
following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for

skeletons.

Understanding requirements for the distributed applications


2

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 have all these features, so it is called the distributed application.

Distributed Applications Architecture


A distributed application is an application comprised of multiple clients that
communicate with servers or machines through a network.

How Do Distributed Applications Work?


Distributed applications interact to achieve a specific goal or task. You can store them
on either servers or cloud infrastructure platforms. Distributed applications can be relatively
simple, involving a single client computer and server, or more complex involving multiple
client computers and servers—it primarily depends on how you plan to use them.

Distributed applications connected over a network


It’s also important to note that some distributed applications are two separate software
programs consisting of front-end (client) and backend (server) applications. The front-end of
the operation runs on the client computer and requires minimal processing power, while the
backend requires a lot more processing power, a more dedicated system, and runs on a server
computer.
In other distributed applications, the functionality separates into smaller, independent
parts. These applications comprise individual microservices that handle different concerns
within the broader application. In a cloud-native environment, the individual components
typically run as containers on a cluster. We’ll go into more detail on how a distributed
application is built later in this blog.
A distributed application is a program that runs on one or more computers
simultaneously and communicates through a network. In this blog post, we’ll dive into how
distributed applications work, how they differ from standalone or traditional applications,
how you can use them, their advantages and disadvantages, and some of the tools and
technologies you can use to build them.

Standalone vs. Distributed Applications


3

Standalone applications rely on a single system to run. Because of this, all processing,
data storage, and retrieval are from a single machine or server. If the application is a client-
server model, the software will run on either the client or the server the client accessed.
These applications are much simpler to maintain and develop and do not require
infrastructure for communication and coordination between different systems. Since the
applications do not rely on a network to communicate, they are not prone to communication
failure due to network faults.
However, this also means these systems have limited capabilities and aren’t scalable.
An application running on a single system is a single point of failure – if the system fails, the
application is no longer available. They can also negatively impact developer velocity as
they grow because more developers need to work on a shared codebase that doesn’t
necessarily have well-defined boundaries.
On the other hand, distributed applications are interconnected machines capable of
processing, data storage, and retrieval through multiple systems. They can run on both the
server and the client simultaneously. The advantage of using distributed applications is that it
provides reliability—if a system running an application goes down, another one can resume
the task. The overall system can tolerate more application faults. They can also
use horizontal scaling, which is impossible with standalone applications. However, these
advantages come at the cost of increased complexity and operational overhead.

How Can I Use Distributed Applications?


Consider applications that run in hospitals, banks, or other service-oriented
organizations. Because the same software runs on multiple computers, it allows people to
work on the same record from the same or different locations editing different aspects of the
record such as logging data, updating addresses, and retrieving transaction information.
Common use cases for distributed applications include:

 Web browsers (Tor)


 E-commerce websites (Amazon, eBay)
 Blockchain applications (Bitcoin, Ethereum)
 Cloud computing platforms (AWS, Microsoft Azure)
 Distributed databases (Couchbase, Apache Cassandra)
 Peer-to-peer file-sharing networks (BitTorrent)

Any application that stores data from one location and retrieves it from another can be
considered a distributed application. To understand what architecture is appropriate for a
particular use case, we should look into the different types of distributed applications a
developer can create.

Distributed Application Examples


Distributed applications leverage the principle of distributed systems. The most
commonly used application architectures can be broadly organized into the following
categories based on their underlying network architectures:

Client-server architecture:
4

This is the most basic distributed system in which the server and client
communicate. Communications include message passing, data collection, and calculations.
 Three-tier architecture: This is a client-server architecture organized into three tiers:
the presentation, application, and data layers. It uses separate layers for each function
of the program. The presentation layer displays the user-facing interface, the
application layer is responsible for accessing and processing data from the database,
and the data layer is where all the data and information are hosted and stored.
 N-tier architecture: This differs from the three-tier architecture because each
function runs on a separate machine or cluster.
Peer-to-peer architecture: In this system, each computer acts as a node for communication.
Working as a node for communication means that each computer is a server and a client. It
doesn’t have a centralized server like the previous architecture. Each system manages itself
in a peer-to-peer network, making it easier to set up and handle.

Microservices architecture: This architecture structures an application as a collection


of small, loosely coupled, and independently deployable services. An application can be
decomposed into highly cohesive services, each representing a specific business capability or
functionality.
Service-oriented architecture: In this approach, applications are built as a collection
of services that communicate with each other through standardized protocols, promoting
loose coupling and reusability of services.

Advantages of Distributed Applications


The advantages of using distributed applications are:
 They have the capability of scaling horizontally. They take advantage of the scaling
features of distributed systems and can expand themselves by adding new servers and
systems that increase the capacity and operations of a network. Horizontal scaling
allows them to easily implement applications on new systems without affecting the
original network.
 They’re tolerant of failures or software faults, making them very resilient. Because the
applications run on multiple systems, it allows them to work independently. A failure
of an application or a breakdown of a machine doesn’t impact the other applications in
the network.
5

 Due to the distributed nature of the application, the response time is much faster,
giving it the advantage of low latency.
 Autonomy is another advantage of distributed applications. As the system shares data,
each user or site retains control over locally stored data and resources. It also reduces
the risk of a system-wide failure or data manipulation.
 Distributed applications can also be cost-effective in the long run, as multiple
computers work together by sharing resources over a network.

Disadvantages of Distributed Applications


The disadvantages of distributed applications are:

 A distributed application introduces increased design complexity. There is a lot of
operational overhead in maintaining, implementing, and troubleshooting issues.
 Using numerous servers, systems, and databases increases the risk of security breaches,
data issues, and information leakage. However, you can counter this by taking security
measures and running protection programs on systems and servers at all locations.
 Since distributed applications connect over a single network, any issues or faults can
lead to a communication breakdown among the applications.
Tools and Technologies for Building Distributed Applications
Building distributed applications requires a fair amount of skill and understanding of
distributed system architectures, frameworks, middleware architecture, and databases. The
tools you choose depend on the application’s requirements, programming languages, and
desired functionality and characteristics.
Most people turn to tools like Docker and Kubernetes for deploying and managing
distributed applications. They provide containerization approaches and orchestration
capabilities for scaling, load balancing, and managing distributed deployments. Cloud
platforms like AWS and Microsoft Azure also have IaaS and SaaS capabilities, making it
possible to use them for building scalable distributed applications

Generating Stubs and Skeletons


Use
You generate stubs and skeletons to provide communication support to your remote
objects. You use the RMIC tool to generate them against the implementation class of the
remote interface.
You need this tool only if you do not use dynamic stubs and skeletons for your remote
objects. For more information about the types of RMI-P4 stubs and skeletons, see Remote
Objects Communication in RMI-P4.
Procedure
1. To start the RMIC tool, run the rmic script file located in the \usr\sap\<system_id>\
<instance_name>\j2ee\deploying directory.
2. To generate RMI-P4 stubs and skeletons, select RMI_P4 Support.
3. In the Additional Classpath field, specify the path to any JAR files or individual
class files that must be added to the classpath.
You can use the PathChooser screen area to browse to the corresponding directories.
You add them to the Additional Classpath field by choosing <<.
6

4. In the Class Name field, specify the fully qualified class name of the
implementation class against which stubs and skeletons are generated. As with
the AccountImpl class, the value of the field must be examples.rmi_p4.AccountImpl.
5. Set any of the following additional options of the RMIC tool if you want to change
their defaults:
a. In the Generator Directory field, specify the path to the directory
where you want the generated Java files to be stored. The path must be absolute.
You can use the PathChooser screen area to browse to the corresponding
directory. You add it to the Generator Directory field by choosing <<.

By default, the generated files are placed in the directory where the RMIC tool
resides.
b. In the Compiler Directory field, specify the path to the directory
where you want the generated Java class files to be stored. The path must be
absolute.
Use the PathChooser screen area to browse to the corresponding directory. You
add it to the Compiler Directory field by choosing <<.

By default, the generated files are placed in the directory where the RMIC tool
resides.
c. To provide additional security functions to the generated skeleton,
select Use RMI-P4 Security.
This type of skeleton checks whether the client requesting the remote method is
authorized to execute this method. If it is not authorized, no access to the remote
method is granted by the system.
d. To store additional information about the application in
the ThreadContext, select Apply Execution Context.
e. To prevent the tool from deleting the files with .java extensions after
it generates the stubs and skeletons, select Keep Java Files.
6. Choose Generate to generate the stubs and skeletons.

Defining Remote Objects


As mentioned earlier, defining a remote RMI object involves specifying a remote
interface for the object, then providing a class that implements this interface. The remote
interface and implementation class are then used by RMI to generate a client stub and server
skeleton for your remote object. The communication between local objects and remote
objects is handled using these client stubs and server skeletons. The relationships among
stubs, skeletons, and the objects that use them
7

Relationships among remote object, stub, and skeleton classes

Methods of Remote Object

bind():
- Binds the specified name to the remote object.
- The name parameter of this method should be in an URL format.

unbind():
- Destroys the binding for a specific name of a remote method in the registry.

rebind():
- Binds again the specified name to the remote object.
- The current binding will be replaced by rebinding.

list():
- Returns the names of the names that were bound to the registry in an array form.
- These names are in the form of URL-formatted string.

lookup():
- A stub, a reference will be returned for the remote object which is related with a specified
name.

Characteristics of a Remote Object


Definition
A remote object is an object that defines methods that can be called by a client located in a
remote Java Virtual Machine (JVM). A remote object implements one or more remote
interfaces that declare remote methods of the object.
Use
8

Consider the following guidelines when you implement the remote interface inherited by the
remote object:
 The implementation class can implement one or more remote interfaces.
 The implementation class can inherit other remote objects.
 The implementation class can declare methods that are not declared by a remote
object; those methods can be called locally only.
Structure
Remote Interfaces and Classes
From RMI-P4 perspective, a remote interface is any interface that inherits
the java.rmi.Remote interface, either directly or indirectly. Each method that such an
interface or its superior interfaces define is considered a remote method.
The following remote interface directly inherits java.rmi.Remote, and defines three remote
methods:

public interface Account extends java.rmi.Remote {


public void deposit(int amount);
public void draw (int amount) throws OverdrawException;
public int getBalance() throws java.rmi.RemoteException;
}
According to the RMI-P4 definition of a remote method, it is not mandatory to
throw java.rmi.RemoteException (as opposed to the RMI specification that requires remote
objects to throw such an exception). However, we recommend that you
declare RemoteException in the throw clauses of your remote methods for the sake of
consistency in exception handling. Also, this avoids the possibility of getting
a com.sap.engine.services.rmi_p4.P4RuntimeException exception when the methods are
executed.
A remote interface can inherit both a non-remote interface and
a java.rmi.Remote interface.
Assume we have the following interface:
public interface Parent {
public void method1();
public void method2() throws java.rmi.RemoteException;
public void method3() throws UserException;
}
The following interface inherits the Parent interface, along with the java.rmi.Remote :
public interface Child extends Parent, java.rmi.Remote {
}
According to the rule above, all the methods of the Parent interface are valid remote
methods.
Parameters Transmitted by Remote Objects
A parameter that is sent to or returned from a remote object can be any serializable
object. These are the primitive Java types, the remote objects, and non-remote objects that
implement java.io.Serializable .
Serialization and Deserialization in Java
1. Serialization
2. Serializable Interface
9

3. Example of Serialization
4. Example of Deserialization
5. Serialization with Inheritance
6. Externalizable interface
7. Serialization and static data member

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


It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is
converted into an object. The serialization and deserialization process is platform-
independent, it means you can serialize an object on one platform and deserialize it on a
different platform.
For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and for deserialization we call the readObject() method
of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
Advantages of Java Serialization
It is mainly used to travel object's state on the network (that is known as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark"
Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be
persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by
default.
Let's see the example given below:
Student.java
ADVERTISEMENT
ADVERTISEMENT
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
10

5. public Student(int id, String name) {


6. this.id = id;
7. this.name = name;
8. }
}
In the above example, Student class implements Serializable interface. Now its objects can
be converted into stream. The main class implementation of is showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
Constructor
1) public ObjectOutputStream(OutputStream It creates an ObjectOutputStream that
out) throws IOException {} writes to the specified OutputStream.
Important Methods
Method Description

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

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

3) public void close() throws IOException {} It closes the current output stream.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor
1) public ObjectInputStream(InputStream It creates an ObjectInputStream that reads
in) throws IOException {} from the specified InputStream.
Important Methods
Method Description

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

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


Example of Java Serialization
In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object. We are saving the state of the object in the file named f.txt.
Persist.java
1. import java.io.*;
2. class Persist{
11

3. public static void main(String args[]){


4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17.}
Output:
ADVERTISEMENT

Success

You might also like