
dhmitchell
Kotlin Coroutine Confidence: TimerApplication: won't app finish before timer?
In the example “timers/v7/src/main/kotlin/com/example/timers/TimerApplication.kt”
Why doesn’t the program just exit after queuing the timer.schedule
rather than waiting for them to callback?
Marked As Solved

sam-cooper
Great question! As I very briefly mention a couple of pages earlier, the java.util.Timer()
class has its own thread, which it uses to run all its callbacks. It’s the existence of this thread which keeps the program running. When we reach the callback, we call timer.cancel()
, which shuts down the timer’s thread and allows the program to exit.
I’ll see if I can update the text to make it a little clearer why the program behaves this way.
The fact that active threads keep the program alive is pretty useful for our Timer
code examples, but it doesn’t have to apply to all threads. You can also configure a thread as a daemon to allow the program to exit without waiting for the thread to finish. You’ll spot that we have to do this for the Retrofit HTTP client we use later on in the same chapter. Setting up all the code examples so that they exit correctly when all our coroutines and callbacks have finished—but not before—was actually a really interesting challenge!
Popular Prag Prog topics










Other popular topics










Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /js
- /rails
- /python
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /haskell
- /emacs
- /svelte
- /onivim
- /typescript
- /crystal
- /c-plus-plus
- /tailwind
- /kotlin
- /gleam
- /react
- /flutter
- /elm
- /ocaml
- /vscode
- /opensuse
- /ash
- /centos
- /php
- /deepseek
- /zig
- /scala
- /html
- /debian
- /nixos
- /lisp
- /agda
- /react-native
- /sublime-text
- /textmate
- /kubuntu
- /arch-linux
- /revery
- /ubuntu
- /manjaro
- /spring
- /django
- /diversity
- /lua
- /nodejs
- /slackware
- /julia
- /c
- /neovim