ipkiss
ipkiss

Reputation: 13661

what make rmi server keep running?

I have the following RMI server code:

public class ServerProgram {
    public ServerProgram() {
        try {
            LocateRegistry.createRegistry(1097);
            Calculator c = new CalculatorImpl();
            String name = "rmi://host:port/name";
            Naming.rebind(name, c);
            System.out.println("Service is bound......");
        } catch (Exception e) {
        }
    }
    public static void main(String[] args) {
        new ServerProgram();
    }
}

When the above program running, it keeps running to wait for client requests. But what I do not understand is what make that program keeps running while it is not in something like while(true){}; and how to stop it from listening, except stopping the whole program?

Upvotes: 10

Views: 3292

Answers (3)

Thor
Thor

Reputation: 6656

But what I do not understand is what make that program keeps running while it is not in something like while(true){}; and how to stop it from listening, except stopping the whole program?

This is done by a edit non-editdaemon thread. See: What is Daemon thread in Java? You can test the behavior with this little example:

public class DaemonThread extends Thread
{
  public void run(){
    System.out.println("Entering run method");
    try
    {
      System.out.println(Thread.currentThread());
      while (true)
      {
        try {Thread.sleep(500);}
        catch (InterruptedException x) {}
        System.out.println("Woke up");
      }
    }
    finally { System.out.println("run finished");}
  }

  public static void main(String[] args) throws InterruptedException{
    System.out.println("Main");
    DaemonThread t = new DaemonThread();
    t.setDaemon(false);  // Set to true for testing
    t.start();
    Thread.sleep(2000);
    System.out.println("Finished");
  }
}

The setting prevents the JVM to shut down. after System.out.println("Finished"); you still see the thread running with it's "Woke up" log outputs.

Upvotes: -2

user207421
user207421

Reputation: 310985

What makes it keep running is a non-daemon listening thread started by RMI. To make it exit, unbind the name and unexport both the Registry and the remote object, with UnicastRemoteObject.unexportObject().

Upvotes: 6

datalost
datalost

Reputation: 3773

To stop it, you should call

LocateRegistry.getRegistry().unbind("rmi://host:port/name");

Upvotes: 1

Related Questions