2013-04-15 2 views
1

Java에서 동시에 다른 URL을 검사하기 위해 다중 스레드를 사용합니다. 요청 시간의 합계가 100,000을 초과하는 경우 버그가있었습니다. 나는 이미 닫아야 할 것을 이미 닫았다. 여기 내 서블릿의 코드는org.apache.http.conn.ConnectionPoolTimeoutException : 풀에서 연결을 기다리는 시간 초과.

여기
private String proyGetHttp(String url) throws ParseException, IOException, 
      InterruptedException { 

     String content = ""; 
     getMethod = new HttpGet(url); 
     HttpResponse response = null; 
     HttpEntity httpEntity = null; 
     boolean success = false; 
     while (!success) { 
      System.out.println("url:" + url + ",connect..."); 
      try { 
       response = client.execute(getMethod); 
       httpEntity = response.getEntity(); 
       StringBuffer sb = new StringBuffer(); 
       if (httpEntity != null) { 
        BufferedReader in = null; 
        InputStream instream = httpEntity.getContent(); 
        try { 
         in = new BufferedReader(new InputStreamReader(instream)); 
         String lineContent = ""; 
         while(lineContent != null){ 
          sb.append(lineContent); 
          lineContent = in.readLine(); 
         } 

        } catch (Exception ex) 
         getMethod.abort(); 
         throw ex; 
        } finally { 
         // Closing the input stream will trigger connection release 
         try { instream.close(); in.close();} catch (Exception ignore) {} 
        } 
       } 
       content = sb.toString(); 
       success = true; 
       System.out.println("connect successfully..."); 
      } catch (Exception e) { 
       e.printStackTrace(); 
       getMethod.abort(); 
       System.out.println("connect fail, please waitting..."); 
       Thread.sleep(sleepTime); 
      }finally{ 
       getMethod.releaseConnection(); 
      } 
     } 
     return content; 
    } 

코드는 기본 클라이언트

 PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); 
     cm.setMaxTotal(100); 
     DefaultHttpClient client = null; 
     client = new DefaultHttpClient(cm); 
     client.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); 
     client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000); 

답변

5

나는이 같은 문제를 가지고 내가 수정을 찾았을 만들 수 있습니다. 이 시간 초과는 연결 유출로 인해 발생합니다. 제 경우에는 httpDelete 메서드를 사용하고 응답을 사용하지 않습니다. 대신 응답 상태를 확인하십시오.

해결 방법은 응답 엔터티를 사용해야한다는 것입니다. 시스템 리소스의 적절한 해제를 보장하기 위해서는 엔티티와 관련된 콘텐츠 스트림을 닫아야합니다.

그래서 EntityUtils.consumeQuietly (response.getEntity());를 사용했습니다. 이는 엔티티 콘텐츠가 완전히 소비되고 콘텐츠 스트림 (존재하는 경우)이 닫히는 것을 보장합니다.

관련 문제