2011. 8. 29. 17:03
작업 실행 시간 제한 JAVA이야기2011. 8. 29. 17:03
실행 중인 작업이 일정한 시간이 지난 이후에도 종료되지 않고 결과를 받지 못한다면, 결과를 사용할 시간이 지나 더 이상 작업의 의미가 없을 경우도 있다.
예) 응답성이 2초 이상이면 동적인 광고보다 정적인 광고를 보여주는게 더 나을 수도 있다.
지정된 시간이 지나면 더 이상 기다려줄 수 없다.
Future 클래스의 get메소드를 이용하면 이를 해결할 수 있다.
예) 응답성이 2초 이상이면 동적인 광고보다 정적인 광고를 보여주는게 더 나을 수도 있다.
지정된 시간이 지나면 더 이상 기다려줄 수 없다.
Future 클래스의 get메소드를 이용하면 이를 해결할 수 있다.
public class RenderPageWithAd {
private static final long TIME_BUDGET = 3000;
private static final TimeUnit NANOSECONDS = TimeUnit.NANOSECONDS;
private static final Ad DEFAULT_AD = new Ad();
private ExecutorService exec = Executors.newFixedThreadPool(100);
Page renderpageWithAd() throws InterruptedException{
long endNanos = System.nanoTime() + TIME_BUDGET;
Future<Ad> f = exec.submit(new FetchAdTask());
Page page = renderPageBody();
Ad ad = null;
try{
long timeLeft = endNanos - System.nanoTime();
ad = f.get(timeLeft, NANOSECONDS);
}catch(ExecutionException e){
ad = DEFAULT_AD;
}catch(TimeoutException e){
ad = DEFAULT_AD;
f.cancel(true);
}
page.setAd(ad);
return page;
}
private Page renderPageBody() {
// TODO Auto-generated method stub
return null;
}
private class Page{
private Ad ad = null;
public void setAd(Ad ad) {
// TODO Auto-generated method stub
this.ad = ad;
}
//ad를 적절한 위치에 그린다.
}
private class Ad{
}
private class FetchAdTask implements Callable<Ad>{
@Override
public Ad call() throws Exception {
// TODO Auto-generated method stub
return null;
}
}
}
'JAVA이야기' 카테고리의 다른 글
스레드 작업중단2 (0) | 2011.09.01 |
---|---|
스레드 중단 및 종료 (0) | 2011.09.01 |
Excutor 프레임웍 (0) | 2011.08.28 |
작업별로 스레드를 만드는 것은 자원관리 측면에서 허점이 있다. (0) | 2011.08.28 |
Barrier (0) | 2011.08.28 |