views:

210

answers:

2

Is there a portable way to request a Servlet container to shutdown gracefully, from within a servlet?

By portable I mean a technique that will work on all standard compliant containers (Tomcat, Jetty, Winstone, etc).

Note that this is the opposite of the Servlet.destroy() method, which gets called when the container is taking the servlet down.

+1  A: 

System.exit();

If you are running with no SecurityManager.

EDIT: Is this graceful? This depends on containers.

On Tomcat, if you call it with 0

  System.exit(0);

It's as graceful as shutdown.sh or Catalina.stop() because the shutdown hook simply calls stop().

ZZ Coder
But is that **graceful** ?
HRJ
On further thought, and in the absence of other solutions, this does seem like a good way. The container could register shutdown hooks with the VM to ensure gracefulness.
HRJ
There are no guarantees the server has registered any shutdown hooks, though. That depends on how the server is implemented. It also has concurrency problems, as requests made simultaneously with the shutdown request can be killed when in an inconsistent state.
gustafc
See my edit .....................
ZZ Coder
Bad, bad idea. Especially in a cloud. But I don't blame ZZ Coder for this answer. The of course, the SecurityManager was mentioned; I just hope anyone taking this advice as a true answer knows what they are doing.
Vineet Reynolds
What would you do if you run out of memory? This is the easiest way to get out of it without complicated monitoring software. We have a daemon will start it right back up.
ZZ Coder
You didn't mention the daemon and I don't think you are running your application in a shared environment.
Vineet Reynolds
+1  A: 

There's no way defined in the Java EE Servlet Spec that I know of, which there would need to be for it to be portable.

The link it to the servlet API specs, so if there's such a way, it'll be documented there somewhere.

I also agree that it'd be a really bad idea for one servlet to be able to shut down the container!

Brabster