메뉴 건너뛰기

tnt_lang

http://javaservice.net/~java/bbs/read.cgi?m=devtip&b=javatip&c=r_p&n=1065062151&p=1&s=t#1065062151예를 들어 고객인지 안닌지를 판별하는 함수  getCust(String aaa)가 참인지 거짓인지를 반환하는 이함수를 호출하여 응답을 기다리는데 5초안에 응답을 하지  않으면 강제로 'false'처리하는 경우...


쓰레드를 하나 만들어서 getCust() 메소드를 호출하시고
그 쓰레드의 상태를 getCust() 메소드를 랩핑한 메소드에서
getCust() 메소드의 실행 상태를 폴링하시면 될듯하네요.

해당 메소드가 빈번하게 호출된다면 좀 문제가 있는 해결책일 수도 있겠습니다.
참고만 하시길..


public class Cust {
    // 폴링 딜레이...(millisecond)
    private static final int POLL_DELAY = 100;

    public static boolean getCust(String id, int delay) throws TimedOutException{
        CustThread ct = new CustThread(id);
        ct.start();

        int timer = 0;
        boolean returnValue = false;
        
        while(true) {

           if (ct.isReturned()) {// getCust()의 실행이 끝났으면
              
               returnValue = ct.getReturnValue();
               break;
           } else {// 아직 끝나지 않았다면

               try {
                    // 좀 쉬어주고
                   Thread.sleep(POLL_DELAY);
               } catch(InterruptedException ie){}
              
                timer += POLL_DELAY;
  
                if (timer > dely) { // 타임 아웃되었는지 체크
                    // 주어진 시간동안 답이 없으면 Exception 발생
                    throw new Exception("TIME_OUT");
                    // return false; <-- 이렇게 하셔도
                }
            }
         } // end of while    
         return returnValue;
     }
    

     static class CustThread extends Thread {
        
         private boolean isReturned = false;
         private String id;
         private boolean returnValue = false;


         public CustThread (String id) {
             this.id = id;
         }

         public void run() {
             /* 실제 getCust(String aaa); 를 사용
             */
             AAA a = new AAA();
             returnValue = a.getCust(id);
             // getCust() 의 실행이 끝났으면 flag 세팅
             isReturned = true;      

         }

         public synchronized boolean isReturned() {
             return isReturned;
         }

         pubilc synchronized boolean getReturnValue() {
             return returnValue;
         }
     }
}



두번째 참고 할 만한 소스
===========================>
폴링하는 것보다는 조금 괜찮은 것 같은 소스입니다.

비슷한게 저도 필요해서

어제 별 생각 없이 책에 있는 거 카피해서 써볼라다가

데드락에 걸려서 고생 좀 했습니다.

약간 수정한 소스고요,  5초동안 Task 가 성공하길 기다리는 소스입니다.

조금 수정하긴 했지만 원본 소스의 아이디어에서 크게 벗어난것은 없습니다.


원본파일 첨부. 출처 :  http://www.amazon.com/exec/obidos/tg/stores/detail/-/books/0672315858/customer-reviews/002-0366056-9156831?show=-rating


public class TestMain {

    public static void main(String[] args){
        final EarlyReturnTest er = new EarlyReturnTest();
                try {

                        Runnable r = new Runnable() {
                                        public void run() {
                                                try {
                                                        er.doWork();
                                                } catch ( Exception x ) {
                                                        x.printStackTrace();
                                                }
                                        }
                                };
                        //먼저 Task 를 실행한다.
                        Thread t = new Thread(r, "Runner");
                        t.setDaemon(true);
                        t.start();
                        
                        long startTime = System.currentTimeMillis();

                        //5초 동안 대기할 것을 시작한다.
                        er.waitUntilAtLeast(5000);
                        long elapsedTime = System.currentTimeMillis() - startTime;
                        System.out.println("after " + elapsedTime +" ms, retVal=" + er.ret);
                } catch ( InterruptedException ix ) {
                        ix.printStackTrace();
                }
    }
}




class EarlyReturnTest {
    String ret=null;
        Exception e=null;
    private Object sync=new Object();
        public EarlyReturnTest() {
        }

        //TASK 실행. 현재 while문이 무한루프를 돌며 응답을 안하게 된다
    private String doProcessWork() throws Exception{
        int k=0;
                while(k<100){
                        k=k+1;
                        k=k-1;
                }
        ret="workend";
        return ret;
    }
        //TASK 를 호출한다. TASK 가 완료될 경우 wating 하고 있는 thread 를 notify한다.
        public void doWork() {
                try{
                        ret = doProcessWork();
                        synchronized(sync){
                                sync.notify();
                        }
                }catch(Exception e){
                        processException(e);
                }
        }
        //TASK 실행중 Exception 이 발생한 경우에도 wating 하고 있는 thread 를 notify한다.
        public void processException(Exception e){
                this.e=e;
                synchronized(sync){
                        sync.notify();
                }
        }
        
        //정한 시간동안 waitng 한다. 혹시나 notify 되더라도 정해진 조건이 만족되지 않으면
        //정한시간에서 지난 시간을 제한후 다시 wait 를 시작한다.
        public void waitUntilAtLeast(long msTimeout) throws InterruptedException {
        long endTime = System.currentTimeMillis() + msTimeout;
        long msRemaining = msTimeout;
        while ( ( ret==null ) && ( msRemaining > 0L ) && (e==null)) {
                        synchronized(sync){
                                sync.wait(msRemaining);
                        }
                        msRemaining = endTime - System.currentTimeMillis();
        }
        }
}




by number501(a)msn.com

--------------------------------------------------------------------------------

번호 제목 글쓴이 날짜 조회 수
38 자바교재소스 운영자 2003.01.29 2269
37 div display, visibility 속성구분 구퍼 2009.01.27 2256
36 클래스 패스와 관련한 문제는 요 jsp 하나로.. 해결 끝이네요.. 하늘과컴 2005.11.15 2228
35 JMSN messenger-한글지원(2/2) file 박상현 2003.12.16 2226
34 셀렉트박스에서 키보드 초성에 해당하는 값 자동select 박상현 2004.08.01 2195
33 Allowed memory Error 처리 구퍼 2010.07.13 2177
32 table 외곽에 테두리만 1pixel로 만들기 운영자 2003.10.01 2168
31 여러가지의 색으로 롤오버 효과및 항목을 선택시 선택된 색을 고정시키는 예제 박상현 2003.11.07 2148
30 테이블의 cell을 이동하는 js file 박상현 2003.12.16 2139
29 Visual c++로 ActiveX작성하고 웹페이지에 붙이는 방법설명.. 운영자 2003.10.09 2138
28 BB설명 운영자 2003.09.26 2126
27 정수값을 3자리수마다 컴마를 찍기 박상현 2003.10.13 2121
26 XMLHTTP설명 박상현 2005.11.11 2110
25 윈도업데이트 이후 실행되지 않았던 activeX 컨트롤 실행 박상현 2005.11.16 2075
24 batch 작업 박상현 2002.02.13 1982
23 WEB-FTP 운영자 2003.10.09 1967
» 시간안에 응답하지 않는함수는 에러(혹은 exception)처리 박상현 2003.10.08 1967
21 드림X 같은 ActiveX 컨트롤을 이용한 컴포넌트 file 박상현 2003.12.15 1944
20 이벤트 종류알기 및 좌표 읽기 박상현 2003.12.03 1935
19 [제로보드] 일반페이지 인증하기 박상현 2003.10.09 1914
위로