endryha
endryha

Reputation: 7256

Shutdown hook of Java process doesn't trigger in gradle daemon

I have a socket server application. This application shutdown server and unbinding from port inside of standard Java shutdown hook when process is stopping :

Runtime.getRuntime().addShutdownHook(new ShutdownHook());

I use application gradle plugin to run it from command line:

apply plugin: 'application'
mainClassName = "com.ServerLauncher"

But when I run application from gradle:

./gradlew :server:run

And then close application with ctrl+z my shutdown hook doesn't trigger.

I guess it's because gradle starts it's own process which starts java process, but it looks like java process doesn't receive shutdown signal.

Upvotes: 3

Views: 5167

Answers (3)

Piotr Kubowicz
Piotr Kubowicz

Reputation: 131

Current Gradle versions use Gradle daemon by default. What actually happens is that after you press Ctrl+C (I think you meant it instead of Ctrl+Z) you don't just terminate your application, you terminate the whole Gradle process. It takes about 10 seconds. Shutdown hooks are executed, but with a delay, and as Gradle is disconnected from console output, you won't see any messages.

Currently the simplest workaround is to add --no-daemon switch.

There is an enhancement proposed to Gradle to fix this behaviour. You can vote for it: https://github.com/gradle/gradle/issues/1128

Upvotes: 3

Radim
Radim

Reputation: 4808

It would be better for you to keep using the daemon as it offers various advantages.

Then there is a possible solution to really stop your application by sending it TERM signal rather than stopping the Gradle process that initiated its execution. Just look at the documentation of kill and jps (or simple ps).

Upvotes: -1

endryha
endryha

Reputation: 7256

I've found solution, to prevent this behavior I need to say gradle not to run it's daemon thread passing this command line argument

./gradlew :server:run --no-daemon

Upvotes: 3

Related Questions