3

I'm converting a Java REST service from the 'traditional' way -- as a servlet compliant .war that deploys to a multi-tenant app server (Tomcat) -- to a much simpler embedded setup where there is a simple Java main class that starts an embedded http server (Grizzly+Jersey). The one missing piece is the service wrapper. I can manually run the service by doing 'java -jar myservice.jar', but I'd like to implement as a proper Linux background service.

Normally, this is done with a simple Bash shell script that you put in /etc/init.d. I've seen some super simple examples, but they implement shutdown with a process kill rather than a graceful shutdown. I've also seen some commerical tools to handle this, but this task seems way too simple to involve a commerical tool.

My first guess would be to add a separate super simple REST service on a second port that listens for shutdown requests and have the /etc/init.d Bash shell script send shutdown requests that way.

Are there better or more standard solutions to this issue?

user2684301
  • 2,550
  • 1
  • 24
  • 33

3 Answers3

2

kill is OK (if it is not kill -9), you should only implement shutdown hook to gracefully stop everithing

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            //TODO stop web server and close db connection if needed

        }
    }));
bedwyr
  • 5,774
  • 4
  • 31
  • 49
JosefN
  • 952
  • 6
  • 8
1

Using a control socket is the standard way to handle graceful shutdown for Unix services that need something more than a signal (e.g., databases). Many of them use a Unix domain socket, but it's becoming common to use HTTP for that sort of thing. You might consider either another HTTP URL with controlled access (either by binding to a different socket or by writing logic to control who can call it) or Java RMI. Neither has an overwhelming advantage over the other.

Note that whatever you're doing probably isn't going to be "REST" and doesn't really need to be; you're going to be running a remote procedure call.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

Are there better or more standard solutions to this issue?

If you don't want to listen for an HTTP call or write your own code that uses sockets, you can use Apache commons-daemon. See the answer here: How to convert a java program to daemon with jsvc?

There's also JSW and YAJSW which are similar.

Community
  • 1
  • 1
John R
  • 2,066
  • 1
  • 11
  • 17