What happens when the JVM is terminated with System.exit(0)
or ^C
or anything of that kind? I read things like "the process is just blown away" and "every single thread is stopped", but I would like to know what happens exactly. I already know there is the shutdownHook
that somehow still gets executed, but what happens before the shutdownHooks are invoked and does anything happen after all these threads have finished?
I would like to implement such a shutdownHook
correctly and to do so I need to make the right assumptions about what might still be executed and what will not.
update:
some code:
class SomeObject {
private boolean stopped;
SomeObject() {
stopped = false;
Thread hook = new Thread() {
@Override
public void run() {
stopped = true;
}
};
hook.setPriority(Thread.MAX_PRIORITY);
Runtime.getRuntime().addShutdownHook(hook);
}
boolean map(Iterator<Object> it) {
while(it.hasNext() && !stopped) {
writeToOtherObject(it.next());
it.remove();
}
//have calculations finished?
return !it.hasNext();
}
}
The map
function computes results that are gathered in some other object. This object should be stored in some file before everything is broken down (by normal-priority shutdownHook
s too). Does the shutdownHook
here make sense? As far I understand it, all threads are destroyed first and only then the shutdownHook
s are run (concurrently, but I assume high-priority threads are run first...) and then objects are finalized. This makes the code above rather useless, because the intention of this shutdownHook
would be to make sure no new loop is started when the shutdown has already started. Is my understanding correct and complete?