ENTERPRISE JAVAHow to Use Jini Distributed Leasing
- By Kathy Kozel
- May 13, 2000
ENTERPRISE JAVA
How to Use Jini Distributed Leasing
Kathy Kozel
Listing 4. Client with manual lease renewal.
import java.rmi.*;
// version 2 clientmanual lease renewal
public class DogClient2 implements Runnable {
private Confirmation confirm;
private Trainable myDog = new Dog();
private Kennel kennel;
private Thread renewalThread;
// how long Dog should stay in kennel (regardless of lease durations)
private long lengthOfStay = 1000 * 60 * 5;
// how much time to allow for a renewal attempt, or taking dog
// back out, prior to the lease expiring.
private long netTravelBuffer = (1000 * 30);
public static void main (String args[]) {
DogClient2 client = new DogClient2();
client.startUp();
}
public void startUp() {
try {
kennel = (Kennel)
Naming.lookup("rmi://127.0.0.1:1099/Kennel");
System.out.println("got the kennel from registry");
confirm = kennel.bookRoom(myDog, lengthOfStay);
System.out.println("We got a lease for " +
confirm.getLease().getExpiration());
System.out.println("we want the dog to stay in for " +
lengthOfStay);
// we got a lease, so start a thread to handle renewals
renewalThread = new Thread(this);
renewalThread.start();
} catch(Exception e) {
e.printStackTrace();
}
} // close startUp
public void run() {
long timeToStop = lengthOfStay + System.currentTimeMillis();
while (true) {
try {
Thread.sleep(calcSleepTime());
}catch(InterruptedException e) {}
if (System.currentTimeMillis() >= timeToStop) break;
try {
renewRoomLease(timeToStop);
}catch(Exception e) {
System.out.println("unable to renew");
e.printStackTrace();
break; //better go get Dog now!
}
} //close loop
retrieveDog();
} // close run
protected void renewRoomLease(long timeToStop) throws
Exception {
confirm.getLease().renew(
(timeToStop - System.currentTimeMillis()) + netTravelBuffer);
System.out.println("successfully renewed");
}
protected void retrieveDog() {
try {
myDog = (Dog) kennel.takeTrainableHome(confirm.getID(),
confirm.getRoomNum());
System.out.println("I got my dog back");
}
catch(Exception e) {
System.out.println("couldn't get my dog!");
e.printStackTrace();
}
}
// calculate how long to sleep safely before trying to renew the
// lease
public long calcSleepTime() {
// determines how long until current lease expires,
// and then allows time to wake up and renew
long nextExpiration = confirm.getLease().getExpiration();
long remainingLeaseDuration =
(nextExpiration - System.currentTimeMillis());
long timeToSleep = remainingLeaseDuration - netTravelBuffer;
if (timeToSleep >= 0)
{
// try to renew now!!
return 0;
}
else
{
return timeToSleep;
}
} // close calcSleepTime
} // close client