Skip to content

Commit

Permalink
#36 - Fix AppLifecycle to remove shutdown hook on close (typically in…
Browse files Browse the repository at this point in the history
… component testing)
  • Loading branch information
rbygrave committed May 19, 2022
1 parent 354c996 commit dff47a2
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions avaje-jex/src/main/java/io/avaje/jex/DefaultLifecycle.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

class DefaultLifecycle implements AppLifecycle {

private static final Logger log = LoggerFactory.getLogger(Jex.class);

private final List<Pair> shutdownRunnable = new ArrayList<>();

private final ReentrantLock lock = new ReentrantLock();

private final AtomicInteger next = new AtomicInteger(1000);
private Status status = Status.STARTING;
private Hook shutdownHook;

@Override
public void onShutdown(Runnable onShutdown) {
onShutdown(onShutdown, 1000);
onShutdown(onShutdown, next.getAndIncrement());
}

@Override
Expand All @@ -35,8 +36,15 @@ public void onShutdown(Runnable onShutdown, int order) {

@Override
public void registerShutdownHook(Runnable onShutdown) {
Hook hook = new Hook(onShutdown);
Runtime.getRuntime().addShutdownHook(hook);
lock.lock();
try {
if (shutdownHook == null) {
shutdownHook = new Hook(onShutdown);
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
} finally {
lock.unlock();
}
}

static class Hook extends Thread {
Expand Down Expand Up @@ -79,9 +87,16 @@ private void fireOnShutdown() {
e.printStackTrace();
}
}
removeShutdownHook();
log.info("Jex shutdown complete");
}

private void removeShutdownHook() {
if (shutdownHook != null) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
}

static class Pair implements Comparable<Pair> {
private final Runnable callback;
private final int order;
Expand Down

0 comments on commit dff47a2

Please sign in to comment.