1

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")
}
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
Beru
  • 657
  • 1
  • 6
  • 21
  • would this answer https://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java – sanjeevRm Apr 13 '21 at 09:38
  • @sanjeevRm I've also seen this answer. Unfortunately it doesn't really help me. I'm curious about why `gradle run` prevents a `Shutdown-Hook` with `Ctrl+C`. – Beru Apr 13 '21 at 09:45

0 Answers0