프로그래밍/Java

[Java] Timer의 Fixed-rate Execution의 함정

Lou Park 2024. 6. 19. 11:31

사건의 발단

앱에서 정확한 시간마다 작업을 수행해야할때 Timer.scheduledAtFixedRate를 사용하던 중, 기이한 로그가 발견되었다. 바로 아주 짧은 시간에 여러번 호출되는 현상!

 

문서를 보면 메소드에 대한 대략적인 설명은 이렇다. 

scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
지정된 시간부터 고정된 간격으로 반복적으로 작업을 수행하도록 예약한다.

 

이 "Fixed-rate execution"에는 함정이있다.

메소드를 눌러 문서를 더 자세히 살펴보면 다음과 같은 문단을 발견할 수 있다.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate). As a consequence of the above, if the scheduled first time is in the past, then any "missed" executions will be scheduled for immediate "catch up" execution.

 

Fixed-rate Execution에서는 백그라운드 활동들이나 GC 수행 등 어떠한 이유로든 작업이 지연된다면 이 뒤쳐진 시간을 따라잡기 위해 즉시 그동안 놓쳤던 작업들을 수행하게 된다는 것이다. 이러한 동작이 일어나기를 원하지 않는다면 schedule 메소드를 사용하는 것이 좋다.

 

 

간단한 코드로 이 동작을 직접 살펴볼 수 있다.