square / retrofit

A type-safe HTTP client for Android and the JVM

Home Page:https://square.github.io/retrofit/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JVM hangs after request completion

tkindy opened this issue · comments

Versions

  • Kotlin: 1.3.40
  • Retrofit: 2.6.0

I created a new Kotlin project and tried to use Retrofit, but it seems to hang the JVM after the main function completes for no apparent reason. I've created a minimal repro in this repo:

fun main() {
    println("Building service")
    val service: ExampleService = Retrofit.Builder()
        .baseUrl("https://example.org")
        .build()
        .create(ExampleService::class.java)

    println("Executing request")
    service.getPage().execute()

    println("Done!")
}

interface ExampleService {
    @GET("/")
    fun getPage(): Call<ResponseBody>
}

All three println statements execute, but then the JVM doesn't immediately finish gracefully. It continues to run for a few minutes, eventually exiting with code 0, but much longer than it should. Is this just an issue on my machine? Am I just doing something incorrect here?

OkHttp, the HTTP client which sits behind Retrofit by default, uses non-daemon threads. This will prevent the JVM from exiting until they time out.

The general pattern for avoiding this scenario is:

client.dispatcher.executorService.shutdown()
client.connectionPool.evictAll()

where client is a manually-instantiated OkHttpClient instance. This goes at the end of main.

Thanks for the tip, that worked like a charm!

Cheers @JakeWharton This is exactly what I was looking for as well.