wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes How to create final action when closing brutally java app Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to create final action when closing brutally java app" Watch "How to create final action when closing brutally java app" New topic
Author

How to create final action when closing brutally java app

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all

say i have application that doing stuff for example creating files

then someone is brutally kill the application by kill -9 or clicking the X in the cmd window

how can i make last action in my application before the application is finally dead?
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
I am not sure you can. kill -9 nameofapp doesn't communicate with the app, it tells the OS to cut the apps throat.

You could write a script to communicate with your app to close files or whatever, and then call kill. I doubt it would be worthwhile to do so especially if your program is used by more then just you and on different platforms, and it still doesn't stop someone from directly invoking kill.

I think the best thing to do is to make sure that the end user won't need to use kill to shut down your program.


"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18711
    
    8

You can use the Runtime.getRuntime().addShutdownHook(Thread) method to specify a Thread that will be started when the application is terminated for any reason. Read its API documentation for all the gory details.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Paul Clapham:
You can use the Runtime.getRuntime().addShutdownHook(Thread) method to specify a Thread that will be started when the application is terminated for any reason.


Any reasonable reason. A kill -9 (SIGKILL) cannot be caught or blocked; there is by definiton nothing Java nor you can do about it.


[Jess in Action][AskingGoodQuestions]
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2716
    
    6

I am aware that the replies posted above are More Experienced and more technical than one would expect.
So i would only like to add in that the above mentioned commands cause abnormal JVM shutdown so even a finally block cannot be helpful at all.


SCJP, SCWCD.
|Asking Good Questions|
 
 
subject: How to create final action when closing brutally java app