add shutdown hook to resolve #1027

This commit is contained in:
Jeremy Long
2017-12-12 06:57:43 -05:00
parent 5fc2fcd7d8
commit 2d9ad67b14
2 changed files with 56 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2017 OWASP.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.owasp.dependencycheck.utils;
/**
*
* @author jeremy
*/
public class H2DBCleanupHook extends Thread {
private final H2DBLock lock;
public H2DBCleanupHook(H2DBLock lock) {
this.lock = lock;
}
@Override
public void run() {
lock.release();
}
}

View File

@@ -68,6 +68,8 @@ public class H2DBLock {
* A random string used to validate the lock.
*/
private final String magic;
private H2DBCleanupHook hook = null;
/**
* Constructs a new H2DB Lock object with the configured settings.
@@ -126,6 +128,7 @@ public class H2DBLock {
lock = null;
LOGGER.debug("Another process obtained a lock first ({})", Thread.currentThread().getName());
} else {
addShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock file created ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
@@ -196,6 +199,7 @@ public class H2DBLock {
}
}
lockFile = null;
removeShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock released ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
@@ -213,4 +217,22 @@ public class H2DBLock {
LOGGER.debug("Lock file age is {} minutes", time);
return time;
}
private void addShutdownHook() {
if (hook == null) {
hook = new H2DBCleanupHook(this);
Runtime.getRuntime().addShutdownHook(hook);
}
}
private void removeShutdownHook() {
if (hook != null) {
try {
Runtime.getRuntime().removeShutdownHook(hook);
} catch (IllegalStateException ex) {
LOGGER.trace("ignore as we are likely shutting down", ex);
}
hook = null;
}
}
}