-
Notifications
You must be signed in to change notification settings - Fork 32
Description
Sometimes, some operation is happening that should not be interrupted by process exit (System.exit(*)). Exiting during these critical operations could result in various undesirable situations, like half-delivered messages, partially written files, or lost data.
Consider providing a "critical section" API that can prevent shutdown for the duration of some operation by centrally managing a single shutdown hook thread. There could be an option to request that the critical section's thread be interrupted if exit occurs.
Semantically, if one or more critical sections is entered when the shutdown hook starts, it will wait until all sections have been exited before letting the thread exit. If the shutdown hook observes no critical sections, it sets a flag preventing further critical sections from being entered (probably by parking the thread indefinitely, as opposed to throwing exceptions which might end up in the log).
The process submodule could be a good location for this, because while it doesn't deal with external processes per se, it does deal directly with the current JVM process.
Some usage examples to reflect design ideas follow.
// this variation has an allocation but no lambda usage
try (var _ = CriticalSection.enter()) {
// ... write the file ...
}// this variation has an allocation plus a lambda, but cannot be escaped
CriticalSection.enter(() -> {
// ... write the file ...
}// this variation is fastest but risks counts getting out of sync from improper usage
CriticalSection.enter();
try {
// ... write the file ...
} finally {
CriticalSection.exit();
}Interruptible variations could be called enterInterruptibly() or we could use a series of flags like NIO does: enter(INTERRUPTIBLY).