Kotlin Coroutine Confidence: TimerApplication: won't app finish before timer?

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!