ExecutorService.submit 메서드로 작업을 등록하면 Future 인스턴스를 리턴 받는다.
Future 에는 cancel() 메서드가 있어서 작업에 취소요청을 줄수 있다.
public class TimedRun {
private static final ExecutorService taskExec = Executors.newCachedThreadPool();
public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException {
Future<?> task = taskExec.submit(r);
try {
task.get(timeout, unit); // 작업결과 얻기 - 타임아웃 지정
} catch (TimeoutException e) {
// Future.get 의 타임아웃에 의해 중단됨.
// 아래 finally의 cancel메서드에 의해 작업이 중단될 예정.
} catch (ExecutionException e) {
// task 작업 수행 중 예외 발생, 예외를 다시 던짐
throw launderThrowable(e.getCause());
} finally {
// task가 이미 완료되었어도 큰 영향 없음
task.cancel(true); // 실행중이라면 인터럽트를 걸어 작업 중단 요청
}
}
}