38

Is it possible to write a method that System.exit will call when you terminate a program?

reevesy
  • 3,452
  • 1
  • 26
  • 23
Alex
  • 5,364
  • 9
  • 54
  • 69

5 Answers5

64

Use Runtime.getRuntime().addShutdownHook(Thread).

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
6

Shutdown hooks are the answer... here is an article on them. They do not come without issues (some of them are discussed in the article).

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
3

You can use a shutdown hook.

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

Note that shutdown hooks will not run if the VM aborts abnormally or Runtime.halt(int) is called.

Dev
  • 11,919
  • 3
  • 40
  • 53
2

Look into shutdown hooks, see http://docs.oracle.com/javase/8/docs/technotes/guides/lang/hook-design.html

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52
2

You can add a VM shutdown hook.

reevesy
  • 3,452
  • 1
  • 26
  • 23
lobster1234
  • 7,679
  • 26
  • 30