0

I'm prototyping a concurrent/distributed system in Java. When a process is terminated (e.g. ctrl+c on command line or red button in Eclipse) I would like to broadcast a message to the other processes (one final method) before it goes away. Tried doing it with finalize() but to no avail. Just pure java with threads, sockets, and a main loop. Thanks.

mstath
  • 111
  • 1
  • 3
  • 9

4 Answers4

7

Have you tried using Runtime.addShutdownHook?

Note the part in the documentation indicating that sometimes the JVM may abort without running shutdown hooks - this should be used as part of graceful shutdown, but shouldn't be assumed to always run. (Imagine if your network is suddenly cut off, for example - you can't broadcast a goodbye message in that case.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Runtime.addShutdownHook() is what you're looking for.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

You can use Runtime.addShutdownHook().

hmjd
  • 120,187
  • 20
  • 207
  • 252
0

Runtime.addShutdownHook() is what you want. This is only runs if the JVM is shutdowns normally

Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44