Whence System.exit()?

A few days ago I was asked how to determine where in a Java program the call System.exit() is made. I came up with the following:

import java.util.Map;

public class TestSystemExit {
    public void methodOne() {

    public void methodTwo() {

    public void methodThree() {
    public void methodFour() {

    public static void printStackTrace(Thread thread, StackTraceElement[] stElmts) {
        System.err.println("thread: " + thread);
        for (StackTraceElement stElmt : stElmts) {
            System.err.println("\tat " + stElmt);

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                Map stMap = Thread.getAllStackTraces();
                // only dump the stack trace with the method "exit":                
                for (Map.Entry stElmt : stMap.entrySet()) {
                    for (StackTraceElement st : stElmt.getValue()) {
                        if ((st.getClassName() + "." + st.getMethodName()).equals("java.lang.System.exit")) {
                            printStackTrace(stElmt.getKey(), stElmt.getValue());
        TestSystemExit tse = new TestSystemExit();

The output is as follows:

thread: Thread[main,5,main]
	at java.lang.Object.wait(Native Method)
	at java.lang.Thread.join(Thread.java:1203)
	at java.lang.Thread.join(Thread.java:1256)
	at java.lang.ApplicationShutdownHooks.run(ApplicationShutdownHooks.java:97)
	at java.lang.Shutdown.runHooks(Shutdown.java:106)
	at java.lang.Shutdown.sequence(Shutdown.java:150)
	at java.lang.Shutdown.exit(Shutdown.java:195)
	at java.lang.Runtime.exit(Runtime.java:107)
	at java.lang.System.exit(System.java:923)
	at TestSystemExit.methodFour(TestSystemExit.java:17)
	at TestSystemExit.methodThree(TestSystemExit.java:13)
	at TestSystemExit.methodTwo(TestSystemExit.java:9)
	at TestSystemExit.methodOne(TestSystemExit.java:5)
	at TestSystemExit.main(TestSystemExit.java:46)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s