728x90
반응형

실무에서 특정 로직의 응답이 특정 시간 안에 빨리 안오면 타임아웃 Exception으로 처리해야해서 아래 코드를 적용했다.

        ExecutorService executorService = null;

        try {
            executorService = Executors.newFixedThreadPool(1);
            Future future = executorService.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    CallingClass exam = new CallingClass();

                    return exam.returnStringArr();
                }
            });
            String[] result = (String[]) future.get(5, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
            executorService.shutdownNow();
        }

 

위 코드는 5초안에 Callable 의 리턴 값이 future.get으로 들어오지 않으면, 타임아웃익셉션으로 떨어지게 된다.

 

하지만 여기서 주의할 점은 TimeoutException에서 executorService를 shutdownNow()로 강제로 종료하려고 해도, 만약 안에서 while(true)같은 무한반복을 하고 있으면, TimeoutException으로 메소드가 종료된 것과는 별개로 Thread가 끝나지 않고, 계속 살아서 로직을 진행한다.

 

그래서 만약에 while(true)로 어떤 작업을 해야한다면, 제일 안쪽 while(true)에 다음과 같이 Thread.currentThread().isInterrupted() 조건문을 넣어서 강제로 while문이 끝나게 해야한다.

class CallingClass {
    public String[] returnStringArr() {
        boolean stop = false;
        while (true) {

            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
                if (stop) {
                    break;
                }
            }
            return new String[]{};
        }
    }
}
반응형

+ Recent posts