PHpullh
학습 라이브러리/Kotlin/그레이스풀 셧다운 (Graceful Shutdown)

KOTLIN · 예외처리

그레이스풀 셧다운 (Graceful Shutdown)

애플리케이션 종료 시 진행 중인 작업을 안전하게 완료하고 리소스를 정리하는 패턴입니다.

예외처리고급graceful-shutdowncleanuplifecyclecoroutines

핵심 설명

애플리케이션 종료 시 진행 중인 작업을 안전하게 완료하고 리소스를 정리하는 패턴입니다.

Kotlin code

import kotlinx.coroutines.*

class AppServer {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private val activeJobs = mutableListOf<Job>()

    fun handleRequest(id: Int) {
        val job = scope.launch {
            println("요청 $id 처리 시작")
            delay(1000)  // 작업 시뮬레이션
            println("요청 $id 처리 완료")
        }
        activeJobs.add(job)
        job.invokeOnCompletion { activeJobs.remove(job) }
    }

    suspend fun shutdown(timeout: Long = 5000) {
        println("셧다운 시작 (활성 작업: ${activeJobs.size})")

        // 새 요청 거부 (scope 취소하지 않고 플래그로)
        println("새 요청 거부 중...")

        // 진행 중인 작업 완료 대기
        withTimeoutOrNull(timeout) {
            activeJobs.forEach { it.join() }
        } ?: run {
            println("타임아웃! 남은 작업 강제 취소")
            scope.cancel()
        }

        println("리소스 정리 중...")
        // DB 연결 종료, 파일 닫기 등
        delay(200)
        println("셧다운 완료")
    }
}

fun main() = runBlocking {
    val server = AppServer()
    repeat(5) { server.handleRequest(it) }
    delay(300)
    server.shutdown(timeout = 3000)
}

학습 팁

Runtime.getRuntime().addShutdownHook에서 셧다운 로직을 호출하면 JVM 종료 시 자동으로 정리됩니다.

주의할 점

셧다운 타임아웃 없이 무한 대기하면 서버가 종료되지 않을 수 있습니다. 항상 타임아웃을 설정하고 초과 시 강제 종료하세요.

자주 묻는 질문

그레이스풀 셧다운 (Graceful Shutdown)란 무엇인가요?

애플리케이션 종료 시 진행 중인 작업을 안전하게 완료하고 리소스를 정리하는 패턴입니다.

그레이스풀 셧다운 (Graceful Shutdown) 학습 시 주의할 점은 무엇인가요?

셧다운 타임아웃 없이 무한 대기하면 서버가 종료되지 않을 수 있습니다. 항상 타임아웃을 설정하고 초과 시 강제 종료하세요.