#java #linux #gradle #jvm #kill
#java #linux #gradle #jvm #убить
Вопрос:
У меня есть следующая задача Gradle
task bootup(type: JavaExec) {
dependsOn build
classpath = sourceSets.main.runtimeClasspath
main = 'org.example.ServerLauncher'
args 'hello'
maxHeapSize '512m'
}
и класс ServerLauncher.java
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();
}
}
Когда я создаю Jar ./gradlew jar
и запускаю java -jar /path/to/exec
в CLI, я могу корректно закрыть исполняемый файл с CTRL C
помощью .
Launcher has started
^CShutdown has triggered
Launcher has closed
но если я запущу ./gradlew bootup
, я не смогу корректно закрыть исполняемый файл с помощью CTRL C
> Task :bootup
Launcher has started
<===========--> 91% EXECUTING [8s]
> :bootup
^C%
Как вы можете видеть triggerShutdown
, не выполняется.
Я предполагаю, что это связано с тем, что процесс разветвляется, когда JavaExec
я пытался отправить различные сигналы уничтожения pid
, но все равно не увенчался успехом.
Как мне запустить shutdownhooks разветвленной среды выполнения?
P.S: Я не хочу менять логику в своем java
коде. Тем не менее, я согласен с изменением определения моей задачи Gradle.