Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to create final action when closing brutally java app

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic