본문 바로가기

JAVA

자바 타임아웃 거는법

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";
}
}

 

future.get(300, TimeUnit.MILLISECONDS); 이부분에서 밀리세컨드기준으로 시간을 설정할수 있다.
출처: https://www.reimaginer.me/entry/Java-Method-Timeout-자바-메서드-타임아웃-만들기-예제 [Reimaginer]