Duration 나노초와 밀리초 사용

dropKick·2024년 4월 17일

개발 이슈

목록 보기
7/14

개요

✅ 타임아웃을 걸기 위해 Duration을 사용해서 시간을 가져왔는데 에러 발생

원인

int timeoutValue = timeout.getNano();
  • Spring HttpComponentsClientHttpRequestFactory setXXTimeout(int timeout)은 int 타입
  • 단순하게 Duration.ofSeconds(x).getNano()를 사용하여 값을 설정하면서 문제가 발생
    • 리턴값이 getNano()인 경우 toMillis() 단위로 변환이 필요

해결

int timeoutValue = Math.toIntExact(timeout.toMillis());

Long -> Int 변환 시 Math.toIntExcact()를 사용해야하는 이유

long bigValue = 2147483648L; // int 범위를 초과
int intValue = Math.toIntExact(bigValue); // ArithmeticException
  • Longint의 최대값이 다르기 때문에 형변환 시 오버플로우 발생 가능
  • Math.toIntExact는 오버플로우 발생 시 런타임 예외를 주기 때문에 필수
profile
안아줘요

0개의 댓글