I am looking for a way to save my progress before exiting a Java runtime. Currently, my script is doing some analysis and then writes them inside of XLSX document. Is there a way to write "exit" or something similar in the console, after which my script would proceed to write to XLSX? Is this achieved through creating threads? I don't have any at the moment, it runs consequently.
Asked
Active
Viewed 89 times
1
-
If I understand you correctly, simplest way to do this would probably be with a shutdown hook https://stackoverflow.com/questions/2975248/how-to-handle-a-sigterm ; instead of writing exit, you would trigger it by pressing cntr-c in the console. – Coderino Javarino Jan 10 '19 at 18:43
-
Possible duplicate of [How to handle a SIGTERM](https://stackoverflow.com/questions/2975248/how-to-handle-a-sigterm) – Frontear Jan 10 '19 at 18:50
-
You also have another option. A really hacky method, but you could use a `try{} finally{}` around your entire `main()` method to ensure that in the `finally` the code will write the xlsx. – Frontear Jan 10 '19 at 18:52
2 Answers
2
You need to add a shutdown hook that is a thread that will trigger every time the runtime exits with exit code 0. You must beware of exiting with another exit code if the program fails or there is a power outage because that will result in data loss.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//write to .xlsx
}));

James Conway
- 339
- 3
- 20
-
1Another hacky way to go about this is wrap your entire program in a `try {} finally {}`, where `finally` will save it. – Frontear Jan 10 '19 at 18:48
-
1
-1
Just read the standart input ( the console ) and do something like if(command.equals("exit") MyMainClass.exit() and create corresponding method with saving the data and then calling System.exit

gygabyte
- 176
- 2
- 12
-
This isn't a good solution. At best, this only helps a very specific kind of program. `Runtime.getRuntime().addShutdownHook(...)` is a better alternative. – Frontear Jan 10 '19 at 18:48
-
In fact thats the only solution with which you can be sure the data has been saved. – gygabyte Jan 10 '19 at 18:50
-
And that's only assuming you use an input stream to detect if the user quits. What about in the event of a gui app? or an app which doesn't actually allow user input, but just does a task and quits? – Frontear Jan 10 '19 at 18:51
-
1Well then its not tha case of thia question. If it just runs and the quits then what would be all this about, right.. – gygabyte Jan 10 '19 at 18:53