How to remotely shutdown a Java RMI Server

后端 未结 2 571
猫巷女王i
猫巷女王i 2021-02-15 16:39

I have a very simple Java RMI Server that looks like the following:

    import java.rmi.*;
    import java.rmi.server.*;

    public class CalculatorImpl extends         


        
2条回答
  •  隐瞒了意图╮
    2021-02-15 16:41

    Actually just unregistering and immediately calling System.exit doesn't shut down cleanly. It basically breaks the connection before informing the client that the message was completed. What works is to start a small thread that shuts down the system like:

    public void quit() throws RemoteException {
      System.out.println("quit");
      Registry registry = LocateRegistry.getRegistry();
      try {
        registry.unbind(_SERVICENAME);
        UnicastRemoteObject.unexportObject(this, false);
      } catch (NotBoundException e) {
        throw new RemoteException("Could not unregister service, quiting anyway", e);
      }
    
      new Thread() {
        @Override
        public void run() {
          System.out.print("Shutting down...");
          try {
            sleep(2000);
          } catch (InterruptedException e) {
            // I don't care
          }
          System.out.println("done");
          System.exit(0);
        }
    
      }.start();
    }
    

    The thread is needed to be able to let something happen in the future while still returning from the quit method.

提交回复
热议问题