Search code examples
javaprocessthrift

How can I re-spawn a thrift server in java after an exception?


I'm new to java and have written a small, but quite important, thrift service in java.

I've noticed that occasionally it'll stop serving without any error messages; it seems that the java process just dies, randomly, without a stack-trace or exception.

What would be the best way to ensure this process stays alive even after an error? Here's the main function, if it will help:

public static void main(String [] args) {
    try {
        MyAppServiceHandler handler = new MyAppServiceHandler();
        MyApp.Processor processor = new MyApp.Processor(handler);
        TServerTransport serverTransport = new TServerSocket(8080);
        TServer server = null;
        server = new TSimpleServer(processor, serverTransport);
        System.out.println("Starting thrift server...");
        server.serve();
    }
    catch (TTransportException e) {
        e.printStackTrace();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Solution

  • I've changed to a better solution.

    My main function in java looks like this:

    public static void main(String [] args) {
        try {
          MyAppServiceHandler handler = new MyAppServiceHandler();
          MyApp.Processor processor = new MyApp.Processor(handler);
          TServerTransport serverTransport = new TServerSocket(8080);
          TServer server = null;
          server = new TSimpleServer(processor, serverTransport);
          System.out.println("Starting thrift server...");
          server.serve();
        }
        catch (TTransportException e) {
          e.printStackTrace();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
    }
    

    This leaves the sever to die, which goes against what I wanted from the original solution. However, the java process/server is now initiated from Supervisor which keeps an eye on the process and respawns it if it dies, whereas the original solution (to use a while loop) would keep the server alive but printing stack traces if there was a problem in connecting to the port, and those error messages would be missed.