티스토리 뷰

반응형

특정 인프라가 불안정해서 때때로 오래 걸리는 메서드가 있다고 가정해보자.

오래걸릴 경우는 무조건 이상 상황이다. 기다리지 않고 다음 일을 진행하는 것이 좋다.

네트워크 단에서 문제를 해결하고 싶지만, 내가 그쪽 코드는 건드리지 못하는 상황에서 메서드에 타임아웃을 거는 방법이 있다.


java.util.concurrent.ExecutorService, java.util.concurrent.Future 를 활용하는 방법이다.


import org.junit.Test;
import java.util.concurrent.*;

public class ExecutorTest {

@Test(expected = TimeoutException.class)
public void executorTest() throws Exception{
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable task = new Callable() {
public Object call() throws Exception {
return sometimesTakeALongTime();
}
};

Future future = executor.submit(task);
future.get(300, TimeUnit.MILLISECONDS);
}

private String sometimesTakeALongTime() throws Exception {
Thread.sleep(400);
return "take a long time";
}
}


참고 : http://stackoverflow.com/questions/1164301/how-do-i-call-some-blocking-method-with-a-timeout-in-java

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함