Skip to content

Commit 5be2e91

Browse files
authored
Merge pull request eugenp#8289 from mona-mohamadinia/BAEL-3520
BAEL-3520: Shutdown Hooks for JVM
2 parents 7cbea4a + 58837c6 commit 5be2e91

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.baeldung.shutdownhook;
2+
3+
import org.junit.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
7+
8+
public class ShutdownHookUnitTest {
9+
10+
@Test
11+
public void givenAHook_WhenShutsDown_ThenHookShouldBeExecuted() {
12+
Thread printingHook = new Thread(() -> System.out.println("In the middle of a shutdown"));
13+
Runtime.getRuntime().addShutdownHook(printingHook);
14+
}
15+
16+
@Test
17+
public void addingAHook_WhenThreadAlreadyStarted_ThenThrowsAnException() {
18+
Thread longRunningHook = new Thread(() -> {
19+
try {
20+
Thread.sleep(300);
21+
} catch (InterruptedException ignored) {}
22+
});
23+
longRunningHook.start();
24+
25+
assertThatThrownBy(() -> Runtime.getRuntime().addShutdownHook(longRunningHook))
26+
.isInstanceOf(IllegalArgumentException.class)
27+
.hasMessage("Hook already running");
28+
}
29+
30+
@Test
31+
public void addingAHook_WhenAlreadyExists_ThenAnExceptionWouldBeThrown() {
32+
Thread unfortunateHook = new Thread(() -> {});
33+
Runtime.getRuntime().addShutdownHook(unfortunateHook);
34+
35+
assertThatThrownBy(() -> Runtime.getRuntime().addShutdownHook(unfortunateHook))
36+
.isInstanceOf(IllegalArgumentException.class)
37+
.hasMessage("Hook previously registered");
38+
}
39+
40+
@Test
41+
public void removeAHook_WhenItIsAlreadyRegistered_ThenWouldDeRegisterTheHook() {
42+
Thread willNotRun = new Thread(() -> System.out.println("Won't run!"));
43+
Runtime.getRuntime().addShutdownHook(willNotRun);
44+
45+
assertThat(Runtime.getRuntime().removeShutdownHook(willNotRun)).isTrue();
46+
}
47+
}

0 commit comments

Comments
 (0)