The Wayback Machine - https://web.archive.org/web/20241115014502/https://www.geeksforgeeks.org/remote-method-invocation-in-java/
Open In App

Remote Method Invocation in Java

Last Updated : 11 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Note:
java.rmi package: Remote Method Invocation (RMI) has been deprecated in Java 9 and later versions, in favor of other remote communication mechanisms like web services or Remote Procedure Calls (RPC).

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
  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:

Java




// Creating a Search interface
import java.rmi.*;
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 java.rmi package. Also, a default constructor needs to be created to throw the java.rmi.RemoteException from its parent constructor in class.

Java




// Java program to implement the Search interface
import java.rmi.*;
import java.rmi.server.*;
public class SearchQuery extends UnicastRemoteObject
                         implements Search
{
    // Default constructor to throw RemoteException
    // from its parent constructor
    SearchQuery() throws RemoteException
    {
        super();
    }
 
    // Implementation of the query interface
    public String query(String search)
                       throws RemoteException
    {
        String result;
        if (search.equals("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




// Java program for server application
import java.rmi.*;
import java.rmi.registry.*;
public class SearchServer
{
    public static void main(String args[])
    {
        try
        {
            // Create an object of the interface
            // implementation class
            Search obj = new SearchQuery();
 
            // rmiregistry within the server JVM with
            // port number 1900
            LocateRegistry.createRegistry(1900);
 
            // Binds the remote object by the name
            // geeksforgeeks
            Naming.rebind("rmi://localhost:1900"+
                          "/geeksforgeeks",obj);
        }
        catch(Exception ae)
        {
            System.out.println(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




// Java program for client application
import java.rmi.*;
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)Naming.lookup("rmi://localhost:1900"+
                                      "/geeksforgeeks");
            answer = access.query(value);
            System.out.println("Article on " + value +
                            " " + answer+" at GeeksforGeeks");
        }
        catch(Exception ae)
        {
            System.out.println(ae);
        }
    }
}


Note: 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

Search.java , SearchQuery.java , SearchServer.java & ClientRequest.java
Important Observations:

  1. RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create the distributed applications in java.
  2. Stub and Skeleton objects are used for communication between the client and server-side.


Similar Reads

Recursive Constructor Invocation in Java
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. Here recursive constructor invocation and stack o
3 min read
Enable Remote Debugging For Java Application Deployed in Kubernetes Environment
During Development, developers have to debug their applications to resolve code problems. In order to debug a java application which is deployed on remote machine in a Kubernetes cluster, first developer has to do some steps to enable its application ready for debugging. Below are the manual steps to enable remote debugging for any java application
2 min read
Fetching Updates From a Remote Repository Using JGit
JGit is a lightweight Java library that can be implemented for Git version control systems. It allows developers to perform Git operations programmatically within Java applications. One of the essential tasks in Git is fetching updates from a remote repository, ensuring that the local repository stays in sync with the remote repository. This articl
3 min read
Pushing changes to a remote repository with JGit
JGit is the lightweight and pure Java library implementing the Git version control system. It can allow the developers to perform Git operations programmatically with Java applications. This article will guide you how to push the changes to a remote repository using JGit in the Maven project. PrerequisitesBasic knowledge of Java and Git. JDK is ins
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Java.math.BigInteger.probablePrime() method in Java
Prerequisite : BigInteger Basics The probablePrime() method will return a Biginteger of bitLength bits which is prime. bitLength is provided as parameter to method probablePrime() and method will return a prime BigInteger of bitLength bits. The probability that a BigInteger returned by this method is composite and does not exceed 2^-100. Syntax: pu
2 min read
Java Clock tickMinutes() method in Java with Examples
java.time.Clock.tickMinutes(ZoneId zone) method is a static method of Clock class that returns the current instant ticking in whole minutes using the best available system clock and the time-zone of that instant is same as the time-zone passed as a parameter. Nanosecond and second fields of the clock are set to zero to round the instant in the whol
3 min read
Java Clock withZone() method in Java with Examples
The java.time.Clock.withZone(ZoneId zone) method is a method of Clock class which returns a clock copy of clock object on which this method is applied, with a different time-zone. If there is a clock and it is required to change the zone of clock but not other properties, then withZone() method is used. This method takes zone as parameter which is
3 min read
Java.lang.Short toString() method in Java with Examples
toString(short) The static toString() method of java.lang.Short returns a new String object representing the specified short. The radix is assumed to be 10.This is a static method hence no object of Short class is required for calling this method. Syntax: public static String toString(short b) Parameters: This method accepts a parameter b which is
2 min read
java.lang.reflect.Method Class in Java
java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to occur when matching the actual parameters to call th
3 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
Java.util.Collections.disjoint() Method in java with Examples
java.util.Collections.disjoint() method is present in java.util.Collections class. It is used to check whether two specified collections are disjoint or not. More formally, two collections are disjoint if they have no elements in common. Syntax: public static boolean disjoint(Collection<?> c1, Collection<?> c2) Parameters : c1 - a colle
3 min read
Java.util.ArrayList.add() Method in Java
Below are the add() methods of ArrayList in Java: boolean add(Object o) : This method appends the specified element to the end of this list. Parameters: object o: The element to be appended to this list. Exception: NA // Java code to illustrate add(Object o) import java.io.*; import java.util.ArrayList; public class ArrayListDemo { public static vo
2 min read
Java.util.ArrayList.addall() method in Java
Below are the addAll() methods of ArrayList in Java: boolean addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the ope
4 min read
Java.util.BitSet.set() method in Java
There are four variants of set() method.This article depicts about all of them, as follows: 1. set(int Index) : This method sets the bit at the specified index to true i.e adds a value. Declaration : public void set(int bitIndex) Parameters : Index : a bit index. Result : This method does not return a value. Exception : IndexOutOfBoundsException :
3 min read
Method Class | getName() Method in Java
The getName() method of java.lang.reflect.Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Syntax: public String getName() Return Value: It returns the name of the method, as String. Example: Method:public vo
3 min read
Method Class | toGenericString() method in Java
The java.lang.reflect.Method.toGenericString() method of Method class returns a string which gives the details of Method, including details of type parameters of the method. Syntax: public String toGenericString() Return Value: This method returns a string which gives the details of Method, including details of type parameters of the method. Below
3 min read
Method Class | getGenericParameterTypes() method in Java
The java.lang.reflect.Method.getGenericParameterTypes() method of Method class returns an array of Type objects that represent the parameter types, declared in method at time of coding. It means that the getGenericParameterTypes() method returns array of parameters that belongs to method object. It returns an array of length 0 if the method object
4 min read
Method Class | isBridge() Method in Java
The java.lang.reflect.Method.isBridge() method is used to check whether a function is a Bridge Function or not. This method returns true if method object is a bridge method otherwise it returns false. Bridge Method: These are methods that create an intermediate layer between the source and the target functions. It is usually used as part of the typ
3 min read
Method Class | getGenericReturnType() Method in Java
The getGenericReturnType() method of java.lang.reflect.Method class returns a Type object that represent the return type, declared in method at time of coding. Hence, getGenericReturnType() method returns the return type of method object. If a formal return type is a parameterized type, the Type object returned for it must accurately reflect the ac
4 min read
Method class isSynthetic() method in Java
java.lang.reflectMethod class help us to get information of a single method on a class or interface. This class also provides access to the methods of classes and invoke them at runtime. isSynthetic() method of Method class: This function checks whether Method Object is a synthetic construct or not. If the method is a synthetic construct then the f
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg