0

Is it possible to figure out, for instance in catch block or anywhere in the code, at any time, if the system has begun a shut down?

Normally the shutdownhooks are fired, but Java runtime cannot guarantee when those will run, so I can't register one to set a flag to read elsewhere.

Is it possible to call some method to figure out if the system has gone into that state? For instnace if someone called System.exit(x) or Runtime.getRuntime().exit(status);

mjs
  • 21,431
  • 31
  • 118
  • 200
  • I see that the system sets a private field in Shutdown class, state to HOOKS or FINALIZERS, I will give it a try to read those properties. – mjs Feb 08 '15 at 11:35
  • 1
    If `System.exit` is called _no more code will be called_. `System.exit` never returns. Even if you could somehow figure whether `System.exit` has been called; your code that figured it out would never be invoked! The only code that will be executed will be code that is in shutdown hooks. – Boris the Spider Feb 08 '15 at 11:35
  • That's not true though, because you can have for isntance executor services which in a shutdown hook can be given rights to shutdown gracefully. Prior to adding shutdown hooks to these, as well as after, it is also obvious that other threads were continuing to run. This can happen probably perhaps if Spring or Hibernate, or other libs have shutdown hooks of their own, allowing certain threads to finish, and possibly improperly, see this: http://stackoverflow.com/questions/28387188/spring-hibernate-adding-a-shutdown-hook-running-prior-to-closing-the-entitymanag/28387777#28387777 – mjs Feb 08 '15 at 11:42
  • 1
    You seem to be concerned that the libraries you are using have improperly implemented shutdown hooks from the state you leave them in. Firstly I doubt it. Secondly, what on earth are you doing? The linked question seems to conclude that if you care about the resources getting persisted in case of catastrophe, then persist them all the time. – Nathan Cooper Feb 08 '15 at 11:47
  • Executor services do not just shutdown, it's in the documentation. So someone is wrong here. – mjs Feb 08 '15 at 12:02

1 Answers1

2

Normally the shutdownhooks are fired,

yes ...

... but Java runtime cannot guarantee when those will run,

It cannot guarantee the order in which they will be run, or that they will complete. But it does guarantee1 to start them all.

... so I can't register one to set a flag to read elsewhere.

It is trivial to a class that will provide a "shutting down" flag. Then just arrange that all of your shutdown hooks to sets the flag. If they all set it, it doesn't matter which shutdown hook gets started first.


1 - This guarantee is not unconditional. There are circumstances when the shutdown hooks won't run at all. For example, if the power goes off, or the JVM is "kill -9"'d.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216