How to Send "CTRL+C" / SIGINT signal to Gradle JavaExec task type forked JVM?

Viewed 406

I have the following Gradle task

task bootup(type: JavaExec) {
  dependsOn build
  classpath = sourceSets.main.runtimeClasspath
  main = 'org.example.ServerLauncher'
  args 'hello'
  maxHeapSize '512m'
}

and the class ServerLauncher.java is

package org.example;

import java.util.concurrent.CountDownLatch;

public class ServerLauncher {
    private final CountDownLatch shutdownHook;
    private final String[] args;

    private ServerLauncher(String[] args) {
        this.args = args;
        this.shutdownHook = new CountDownLatch(1);
    }

    public static void main(String[] args) throws Exception {
        new ServerLauncher(args).execute();
    }

    private void execute() throws Exception {
        hangShutdownHook();
        System.out.println("Launcher has started");
        try {
            shutdownHook.await();
        } finally {
            System.out.println("Launcher has closed");
        }
    }

    private void hangShutdownHook() {
        Thread thread = new Thread(this::triggerShutdown);
        Runtime.getRuntime().addShutdownHook(thread);
    }

    private void triggerShutdown() {
        System.out.println("Shutdown has triggered");
        shutdownHook.countDown();
    }
}

When I build the Jar ./gradlew jar and run java -jar /path/to/exec in the CLI, I'm able to close the executable gracefully with CTRL+C.

Launcher has started
^CShutdown has triggered
Launcher has closed

but if I run ./gradlew bootup I'm not able to close the executable gracefully with CTRL+C

> Task :bootup
Launcher has started
<===========--> 91% EXECUTING [8s]
> :bootup
^C%

As you can see triggerShutdown isn't executed.

I'm assuming this is because the process is forked during JavaExec I tried to send various kill signals to the pid, but still wasn't successful.

How do I trigger a forked Runtime's shutdownhooks?

P.S: I don't want to change the logic in my java code. However, I'm okay with changing my Gradle task definition.

0 Answers
Related