what make rmi server keep running?

为君一笑 提交于 2019-12-08 15:45:30

问题


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?


回答1:


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().




回答2:


To stop it, you should call

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



回答3:


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.



来源:https://stackoverflow.com/questions/7446035/what-make-rmi-server-keep-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!