I have a program which implements a Shutdown Hook
in order to ensure everything is closed before the program terminates. If I launch the program from terminal the Shutdown Hook is executed after I press Ctrl+C
. However if I launch the program with gradle run
this doesn't happen.
Questions:
- Why does this happen?
- Is it possible to ensure that the shutdown hook gets executed when I run the program with gradle?
Code:
import java.util.Scanner;
public class MyShutdownHook {
public static void main(String[] args) {
System.out.println("Adding a shutdown hook");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Shutdown hook was being called.");
}));
System.out.println("Enter Exit to terminate the programm.");
Scanner scanner = new Scanner(System.in);
boolean isRunning = true;
while (isRunning) {
if (scanner.hasNext()) {
String answer = scanner.next();
if (answer.equals("Exit")) isRunning = false;
}
}
}
}
Gradle:
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
run {
standardInput = System.in
}
application {
mainClass.set("MyShutdownHook")
}