BAEL-3525: System.exit() vs Runtime.getRuntime().halt()

This commit is contained in:
Kamlesh Kumar 2019-12-01 13:25:55 +05:30
parent c865567b71
commit 35c0ef7f14
3 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package com.baeldung.exitvshalt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JvmExitAndHaltDemo {
private static Logger LOGGER = LoggerFactory.getLogger(JvmExitAndHaltDemo.class);
static {
Runtime.getRuntime()
.addShutdownHook(new Thread(() -> {
LOGGER.info("Shutdown hook initiated.");
}));
}
public void processAndExit() {
process();
LOGGER.info("Calling System.exit().");
System.exit(0);
}
public void processAndHalt() {
process();
LOGGER.info("Calling Runtime.getRuntime().halt().");
Runtime.getRuntime()
.halt(0);
}
private void process() {
LOGGER.info("Process started.");
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.exitvshalt;
import org.junit.Test;
public class JvmExitDemoUnitTest {
JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo();
@Test
public void givenProcessComplete_whenExitCalled_thenTriggerShutdownHook() {
jvmExitAndHaltDemo.processAndExit();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.exitvshalt;
import org.junit.Test;
public class JvmHaltDemoUnitTest {
JvmExitAndHaltDemo jvmExitAndHaltDemo = new JvmExitAndHaltDemo();
@Test
public void givenProcessComplete_whenHaltCalled_thenDoNotTriggerShutdownHook() {
jvmExitAndHaltDemo.processAndHalt();
}
}