Hello friends! I've observed that when I press ctr...
# ktor
s
Hello friends! I've observed that when I press ctrl+c to stop a ktor application from running it takes a little while until it stops.Do you know why? Is there a way to make it instant ? Also the same is true when I start/restart an application from intellij idea: I press the stop button and it takes some seconds until it really stops
c
Could be multiple things. One of them is that Gradle isn't instant. There's also a good chance that Ktor has JVM shutdown hooks to free the network resources back to the OS.
s
thank you for the answer; please notice that this happens when I am packaging the app as a fat jar so it probably isn't related to gradle
so probably it's the 2nd thing you mention about the jvm shutdown hooks
c
I have no idea how to profile them, though 😕
s
no problem thank you
a
If Ktor's server backend is on the critical path to JVM shutdown, you can try asking it to shutdown immediately.
Copy code
val engine = embeddedServer(Netty, port) {
    installApp()
}.start()

// wait

engine.stop(0, 0, TimeUnit.MILLISECONDS)
If that doesn't help, you can try another backend (see supported backends here). If that doesn't help, you may have other background threads delaying shutdown.
s
@Andrew O'Hara thanks for the tip; is there a way to run the engine.stop() when ctrl+c is pressed ? or i need a different way to do that ?
c
Even if you could, I don't think it's a good idea. If it is shutdown hooks that are slowing you down (either from Ktor or another library), they're probably here for a good reason, and it's probably not a good idea to cancel them unless you know for sure it won't lead to data loss. For example, shutdown hooks can be used to save files, export logs, wait for ongoing DB requests to finish... I don't know if Ktor in particular does that, however
s
Excellent thank you
a
Yeah, Ivan has a point; there's often no good reason to interrupt whatever shutdown hooks are running. That being said, YMMV with this, but you could try adding your own shutdown hook to ask ktor to shut down immediately.
s
Thank you I'll give it a try!
148 Views