harshit
harshit

Reputation: 7951

How to capture System.exit event?

I have an application in java, in which i try to ensure that the if anybody exits codes System.exit() in the code , an listener should be called to do some stuff like logging message and releasing the resources ...

How can i implement it, any suggestion/approach is welcome.

Upvotes: 27

Views: 35279

Answers (3)

eckes
eckes

Reputation: 10423

You can also use a JFR recording, the jdk.Shutdown event is enabled=true and stackTrace=true by default. So using jfr print --verbose --events jdk.Shutdown --stack-depth 20 recording.jfc will show you the caller stack trace.

A minimal recording to do this would be (linebreaks for readability):

java -XX:StartFlightRecording:settings=none,filename=recording.jfr, \
  +jdk.Shutdown#enabled=true,+jdk.Shutdown#stackTrace=true \
  SelfExit.java

or for a already running JVM (you need to provide the process id) until the next restart (recent versions have JFR enabled):

jcmd $PID JFR.start settings=none +jdk.Shutdown#enabled=true filename=shutdown.jfr dumponexit=true name=shut

Upvotes: 1

coobird
coobird

Reputation: 161012

The Runtime.addShutdownHook method can be used to add a shutdown hook, which is basically a unstarted Thread, which executes on shutdown of the Java Virtual Machine.

However, this is territory that should to be tread carefully, as it is being performed at a very sensitive time of the JVM's life cycle. From the API Specifications for the Runtime.addShutdownHook method:

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible.

In any event, be sure to read up a bit on how shutdown hooks work, as they probably should not be approached without some good preparation. Be sure to carefully read the API Specification for the Runtime.addShutdownHook method.

Here's are a couple articles I found from searching for information for this answer:

Upvotes: 54

Silfverstrom
Silfverstrom

Reputation: 29338

The function Runtime.addShutdownHook(Thread thehook) allows you to register a hook into the Java Virtual Machine.
The hook works as an initialized but unstarted thread, which will be called by the JVM on exit. In case you register more than one hook, note that the order in which the hooks are called is undefined.

Upvotes: 7

Related Questions