Shutting Down the Java App Gracefully
My first shutdown approach was calling
System.exit(0). Although this method called all the registered shutdown hooks concurrently and tried to shutdown the JVM gracefully, it failed to clean the pipe communication that the Windows service established with the SCM. So when I used the
System.exit call, I got the following error while stopping the service:
System error 109 has occurred.
The pipe has been ended.
I figured out a better way: implement a separate shutdown method and call it. The framework proposed in this article invokes the public static void shutdown() method (if it is implemented) in a separate shutdown thread with a timeout of 20 seconds. This prevents the service from reaching a "not responding" state if the shutdown method never returns. You can configure the timeout period based on your own needs, but make sure it is less than the system timeout. Otherwise, the SCM will terminate your service process.
Beyond the Windows Service
Understanding JNI invocation API provides the flexibility to call Java apps in your C/C++ program. For instance, you may want to provide a web interface to your legacy C application by embedding a Jetty Servlet engine.