Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 272
  • Last Modified:

Making sure a method is called when an application exits

I have a question about how Java works. I know you can have a finalize method to call when an object is being garbage collected to free up some resources to avoid a memory leak.

However, let us assume I have a program as such,

public class Test {

   public static void main (String [] args) {

      while (true) {

         ...
      }
   }
}

that design or a server design where the server waits for a connection forever until it is shutdown by the user. So, when I run this program I have to shut it down by using a Ctrl + C key. Is there a way I can make sure a method is called before the program exits so that I can free up some or call some required resources?

Thanks and if I get a great answer (that solves this problem), I'll definitely add extra points.

Thanks

AJ
0
aratani
Asked:
aratani
  • 2
  • 2
1 Solution
 
CEHJCommented:
Don't use finalizers - unreliable. Use shutdown hook:

http://java.sun.com/developer/TechTips/2000/tt0711.html
0
 
kiranhkCommented:
you can also have a finally block after a try block. this makes sure that whatever hapens the code in the finally block will be called always before exiting.
0
 
arataniAuthor Commented:
A finally block is NOT called if you exit the program by using Ctrl + C or through the task bar.

AJ
0
 
arataniAuthor Commented:
Thanks CEHJ, the shutdown hook worked perfectly. I increased the points and am accepting your result.

AJ
0
 
CEHJCommented:
:-)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now