views:

291

answers:

2

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();
    }
}
A: 

if the call to serve is blocking you can do:

public static void main(String [] args) {
   while(true){
    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();
    }
    //do cleanup
  }
}
MahdeTo
A: 

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.

digitala