0
public class Test {
    public static void main(String[] args)  
    {
        while(true) {
            System.out.println("1 ");
        }
    }
}

What this code does is run for infinite till the program is terminated manually for example give the picture below.enter image description here

What my requirement is when I manually terminate the execution my output should be like below

1 1 1 Program terminated manually thank you

The above 2 lines of output after I manually terminate the program. Why I need this is I am storing the serializable objects in the file. My code flow is when I working on the program there will be a lot of modifications in the object at end of execution I serialize the updated object into the file. So when I terminate the program manually serialization of the updated object is not done. So I need Serialization should be done even at manual termination.

  • Does this answer your question? [Calling function when program exits in java](https://stackoverflow.com/questions/63687/calling-function-when-program-exits-in-java) – Wais Kamal Mar 27 '22 at 06:45
  • I don't think there is any way to handle the Eclipse terminate button, it just kills the JVM process immediately. – greg-449 Mar 27 '22 at 06:59
  • Note: running code from within Eclipse is only intended for testing. If you run the java program from the command line you can use the shutdown hook to deal with Ctrl+C termination. – greg-449 Mar 27 '22 at 09:50

1 Answers1

0

You can add a hook to the shutdown event:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        //Do something here
    }));

Edit: This doesn't work with eclipse, according to greg-449

wewejay
  • 149
  • 1
  • 8
  • 1
    The terminate button in Eclipse forces the program to abort immediately, the shutdown hook is not run. – greg-449 Mar 27 '22 at 06:48
  • Sorry I am not really familiar with eclipse, it worked in Idea, so I thought it would work here too. Thank you. – wewejay Mar 27 '22 at 06:53