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:
- Implement the java.rmi.server.Unreferenced interface in your RMI server.
- Provide an implementation for the unreferenced() method.
- 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.
- 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