Задать вопрос
@alashkov83

Почему не завершается приложение (console+kotlin coroutines+retrofit)?

Почему не завершается приложение (console+kotlin coroutines+retrofit)?
import com.google.gson.annotations.SerializedName
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path

data class Place (
    @SerializedName("place name")
    val place_name: String,
    val longitude: String,
    val state: String,
    @SerializedName("state abbreviation")
    val state_abbreviation: String,
    val latitude: String
)
data class ZipCode(
    @SerializedName("post code")
    val post_code: String,
    val country: String,
    @SerializedName("country abbreviation")
    val country_abbreviation: String,
    val places: Array<Place>
)
interface GameApiService {
    @GET("{country}/{code}")
    suspend fun getGames(@Path("country") country: String, @Path("code") code: Int): Response<ZipCode>
}

suspend fun main(): Unit = runBlocking {
    val retrofit = Retrofit.Builder()
        .baseUrl("https://api.zippopotam.us/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val jokeApiService = retrofit.create(GameApiService::class.java)
    val job: Deferred<Response<ZipCode>> = async(Dispatchers.IO) {
            jokeApiService.getGames("ru", 140100)
    }
    val zipcode = job.await()
    if (zipcode.isSuccessful)
        println(zipcode.body())
    //exitProcess(0)
}
  • Вопрос задан
  • 98 просмотров
Подписаться 1 Простой Комментировать
Помогут разобраться в теме Все курсы
  • Академия Эдюсон
    Android-разработчик + ИИ
    6 месяцев
    Далее
  • Нетология
    Android-разработчик
    14 месяцев
    Далее
  • Merion Academy
    Комплект курсов «Онлайн-курс программирования на Kotlin» и «Java-разработчик с нуля»
    4 месяца
    Далее
Пригласить эксперта
Ответы на вопрос 1
@Sharque
Программис
Висит OkHttp, который Retrofit создаёт под капотом, корутины тут ни при чём. У Dispatcher в OkHttp потоки не daemon и живут 60 секунд без работы, поэтому процесс завершается примерно через минуту после запроса. Я делаю клиент явно и гашу его в конце:

fun main() = runBlocking {
    val client = OkHttpClient()
    val api = Retrofit.Builder()
        .baseUrl("https://api.zippopotam.us/")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(GameApiService::class.java)
    try {
        val zip = api.getGames("ru", 140100)
        if (zip.isSuccessful) println(zip.body())
    } finally {
        client.dispatcher.executorService.shutdown()
        client.connectionPool.evictAll()
    }
}


Когда непонятно, кто держит процесс, я снимаю дамп потоков (jcmd PID Thread.print) и смотрю потоки без пометки daemon. Здесь сразу видно "OkHttp Dispatcher".

Сейчас я это делаю через свой MCP-сервер javaperf (https://github.com/theSharque/mcp-jperf), я автор. Сделал его, когда разгонял бэкенд под нагрузочными тестами, и он помог найти все горячие места. analyze_threads снимает и разбирает дамп, так что можно просто спросить агента, почему процесс не завершается.

{ "mcpServers": { "javaperf": { "command": "npx", "args": ["-y", "javaperf"] } } }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы