Search code examples
javacommand-line-interfaceconsole-applicationsystemexit

How to exit from an endless Java program and print a message?


Say I have a java program (actually I wrote a CLI) which goes into an endless loop and within that loop it's incrementing a counter. When I hit Ctrl + C from my command line to exit from the program, can I print the value of the counter and then exit? Say I have a function like:

public void count(){
    int count = 1;
    while (count>0) {
        count++;
    }
}

Now, I invoke this bit of code and the execution begins. After a while, I hit Ctrl + C on the terminal and the program is forced to exit. While it exits, can I somehow print the value of count and then exit?

Note: I'm not doing this exactly in my program. I'm just trying to figure out if there's a way I can force exit a program and upon force exit print something to the console.


Solution

  • Slight copy pasta from another site (StackOverflow prefers answers here though)

    public class Main {
      public static var message; //can be String, int, whatever.
      static class ForceClosedMessage extends Thread {
        public void run() {
          System.out.println(message);
        }
      }
      public static void main(String... args) {
        Runtime.getRuntime().addShutdownHook(newForceClosedMessage());
        //Go about your business
      }
    }