How to remotely shutdown a Java RMI Server

后端 未结 2 575
猫巷女王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.

    0 讨论(0)
  • 2021-02-15 17:03

    In case anyone is having a similar problem, I figured out the answer myself. Here is my exit() method:

    public void exit() throws RemoteException
    {
        try{
            // Unregister ourself
            Naming.unbind(mServerName);
    
            // Unexport; this will also remove us from the RMI runtime
            UnicastRemoteObject.unexportObject(this, true);
    
            System.out.println("CalculatorServer exiting.");
        }
        catch(Exception e){}
    }
    
    0 讨论(0)
提交回复
热议问题