Skip to content

Commit 7cbea4a

Browse files
authored
Merge pull request eugenp#8281 from kamleshkr/BAEL-3525
BAEL-3525: System.exit() vs Runtime.getRuntime().halt()
2 parents e08dfcc + 2c63519 commit 7cbea4a

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.exitvshalt;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
public class JvmExitAndHaltDemo {
7+
8+
private static Logger LOGGER = LoggerFactory.getLogger(JvmExitAndHaltDemo.class);
9+
10+
static {
11+
Runtime.getRuntime()
12+
.addShutdownHook(new Thread(() -> {
13+
LOGGER.info("Shutdown hook initiated.");
14+
}));
15+
}
16+
17+
public void processAndExit() {
18+
process();
19+
LOGGER.info("Calling System.exit().");
20+
System.exit(0);
21+
}
22+
23+
public void processAndHalt() {
24+
process();
25+
LOGGER.info("Calling Runtime.getRuntime().halt().");
26+
Runtime.getRuntime()
27+
.halt(0);
28+
}
29+
30+
private void process() {
31+
LOGGER.info("Process started.");
32+
}
33+
34+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.exitvshalt;
2+
3+
import org.junit.Test;
4+
5+
public class JvmExitDemoUnitTest {
6+
7+
JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo();
8+
9+
@Test
10+
public void givenProcessComplete_whenExitCalled_thenTriggerShutdownHook() {
11+
jvmExitAndHaltDemo.processAndExit();
12+
}
13+
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.exitvshalt;
2+
3+
import org.junit.Test;
4+
5+
public class JvmHaltDemoUnitTest {
6+
7+
JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo();
8+
9+
@Test
10+
public void givenProcessComplete_whenHaltCalled_thenDoNotTriggerShutdownHook() {
11+
jvmExitAndHaltDemo.processAndHalt();
12+
}
13+
14+
}

0 commit comments

Comments
 (0)