devxlogo

Raising Notifications from RMI

Raising Notifications from RMI

Ever wish you could have your RMI application notify you when it’s using the distributed garbage collector? Sometimes it’s useful to know when a RMI server “kills” an object. Just perform the following steps:

  1. Implement the java.rmi.server.Unreferenced interface in your RMI server.
  2. Provide an implementation for the unreferenced() method.
  3. Specify a value for the java.rmi.dgc.leaveValue system property. This value represents miliseconds (default ten minutes) and it is used to tell how much time must pass without clients interaction before an object is collected.
  4. The client’s interaction represents a “lease contract” that must be updated.

What follows is an example of an RMI server that returns the timestamp of a collected object:

import java.rmi.*;import java.rmi.server.*;import java.util.Properties;public class SumImpl extends UnicastRemoteObject implements SumInterface,Unreferenced{   public SumaImpl()throws RemoteException   {      //optional      super();   }   //the SumInterface method   public int Sum(int a,int b)throws RemoteException{      return (a+b);     }   //the unreferenced method   public void unreferenced()   {      java.util.Date date=new java.util.Date();      System.out.println("Unreferenced called..."+date);   }   //the finalize method   public void finalize()throws Throwable   {      super.finalize();      java.util.Date date=new java.util.Date();      System.out.println("Finalize called..."+date);   }   public static void main(String[] args)   {                    SumImpl SI=null;      //create the remote object      try{         SI=new SumImpl();             }catch(java.rmi.RemoteException e)         {System.out.println(e.getMessage());}      	      try{                 Naming.bind("rmi://localhost:1099/SUMObject",SI);      }catch(java.rmi.AlreadyBoundException e)         {System.out.println(e.getMessage());      }catch(java.net.MalformedURLException e)         {System.out.println(e.getMessage());      }catch(java.rmi.RemoteException e)         {System.out.println(e.getMessage());}               }}

The SumInterface is a simple interface that contains a single method, called Sum. Write this interface and a clasic RMI client, and run the RMI server like this:

<HOME>java ?Djava.rmi.dgc.leaveValue=1000 SumImpl
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist