Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JVM hangs after request completion #3144

Closed
tkindy opened this issue Jul 3, 2019 · 3 comments
Closed

JVM hangs after request completion #3144

tkindy opened this issue Jul 3, 2019 · 3 comments

Comments

@tkindy
Copy link

tkindy commented Jul 3, 2019

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?

@JakeWharton
Copy link
Member

JakeWharton commented Jul 4, 2019

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.

@tkindy
Copy link
Author

tkindy commented Jul 4, 2019

Thanks for the tip, that worked like a charm!

@grahamjenson
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants