Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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