Friday, July 17, 2009

Replacing jsvc for Java daemons

For some time I have been using the Apache Commons Daemon project to run and maintain my Java based services. jsvc did/does a reasonable job but I start to worry when a project has not been touched for a while.

In addition I am in the midst of deploying a Java based service on Mac OS X and so I am in the world of launchd. I wanted a better way of controlling Java based services; particularly one that did not fork multiple processes given launchd's garbage collection.

The principal issue with a Java service running in the background is that you need to have it respond asynchronously to various singals; particularly SIGTERM which of course is issued when the OS is being shutdown. My service needs to shut down gracefully.

Enter in a feature of Java 1.4.2 that I did not realise existed: Shutdown Hooks. In essence Shutdown Hooks provides your Java application an opportunity to respond to the application quitting.

Followers of this blog know that I am an Apache Camel addict. You will not therefore be surprised to find that what follows is an example of how to start up and shutdown a Camel context using Java's Shutdown Hooks.


public class EntryPoint {
static Logger logger =
Logger.getLogger(EntryPoint.class.getName());

static EntryPoint entryPoint;

Main main;

public static void main(String[] args) {
entryPoint = new EntryPoint();

Runtime.getRuntime()
.addShutdownHook(new Thread() {
public void run() {
try {
entryPoint.stop();
} catch (Exception e) {
logger.fatal(e.toString());
}
}
});

try {
entryPoint.start();
} catch (Exception e) {
logger.fatal(e.toString());
}

}

public void start() throws Exception {
logger.info("Starting up");

// Start up the context
main = new Main();
main.start();

logger.info("Started");
}

public void stop() throws Exception {
logger.info("Stopping");

// Shutdown the context
main.stop();

logger.info("Stopped");
}
}

1 comment:

Christopher said...

Update to this post - instead of crafting your own entry point class with Camel you can use the org.apache.camel.spring.Main class directly. This class accommodates the shutdown hooks mentioned.

Go Camel.