Unregister ShutdownHook when GC#PidLock is closed

Otherwise the JVM will accumulate the ShutdownHook objects of all GCs
run while the JVM is up.

Change-Id: Iadc723a939238a3a75b4ba47f898918eb4554ea3
This commit is contained in:
Matthias Sohn 2023-09-08 02:32:57 +02:00
parent e908e297db
commit f94be665f1
1 changed files with 11 additions and 2 deletions

View File

@ -1799,6 +1799,8 @@ private class PidLock implements AutoCloseable {
private FileChannel channel;
private Thread cleanupHook;
PidLock() {
pidFile = repo.getDirectory().toPath().resolve(GC_PID);
}
@ -1827,9 +1829,9 @@ boolean lock() throws IOException {
}
channel.write(ByteBuffer
.wrap(getProcDesc().getBytes(StandardCharsets.UTF_8)));
Thread cleanupHook = new Thread(() -> close());
try {
Runtime.getRuntime().addShutdownHook(cleanupHook);
Runtime.getRuntime().addShutdownHook(
cleanupHook = new Thread(() -> close()));
} catch (IllegalStateException e) {
// ignore - the VM is already shutting down
}
@ -1901,6 +1903,13 @@ private String getHostName() {
public void close() {
boolean wasLocked = false;
try {
if (cleanupHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(cleanupHook);
} catch (IllegalStateException e) {
// ignore - the VM is already shutting down
}
}
if (lock != null && lock.isValid()) {
lock.release();
wasLocked = true;