2014-04-06 4 views
0

위치 데이터가 포함 된 약 10 개의 목록이 있으며 각 목록에는 10.000 개의 항목이 있습니다. 나는 executer 서비스를 시작하여 모든 작업을 처리합니다.스레딩 HttpUrlConnection

ExecutorService executor = Executors.newFixedThreadPool(locationLocationList.size()); 

for(List<Location> locationList: locationLocationList){ 
    executor.execute(new TestThread(locationList)); 
} 

10 개의 스레드에서 작업을 완료하는 데 너무 오래 걸립니다. 가장 비싼 부분은 URL을 열고 연결하는 것 같습니다. 아무도 내가 이걸 어떻게 조정할 수 있을지 생각하지 않아?

@Override 
     public void run() { 
      while(isRunning){ 
       Gson gson = new Gson(); 

      Map<Integer, Data> map= new HashMap<Integer, Data>(); 

      for(Location location: locations){ 
       String data = getJSON(location.getLatitude(), location.getLongitude()); 
       Data data= gson.fromJson(data, Data.class); 
       map.put(location.getId(), data); 

      } 


      weatherDao.setWeatherFast(map); 
      isRunning = false; 
     }      
    } 

    private String getJSON(double latitude, double longitude) { 
     HttpURLConnection httpUrlConnection = null; 

     try { 
      URL u = new URL("someurl"+latitude+""+longitude); 
      httpUrlConnection = (HttpURLConnection) u.openConnection(); 
      httpUrlConnection.setRequestMethod("GET"); 
      httpUrlConnection.setRequestProperty("Content-length", "0"); 
      httpUrlConnection.connect(); 
      int status = httpUrlConnection.getResponseCode(); 

      switch (status) { 
       case 200: 
       case 201: 
        BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream())); 
        StringBuilder sb = new StringBuilder(); 
        String line; 

        while ((line = br.readLine()) != null) { 
         sb.append(line+"\n"); 
        } 
        br.close(); 
        return sb.toString(); 
      } 

     } catch (Exception ex) { 
      LOGGER.error("Couldnt get Data", ex); 
     } 

     return ""; 
    } 

답변

0

에 따를 절차 :

  • 스토어 LatitudeLongitude에 따라 getJSON() 방법의 결과입니다.

  • 각 호출에 대해 저장된지도가있는 경우 먼저 확인하고 getJSON() 메서드를 다시 호출 할 필요가 없습니다.

LatitudeLongitude이 반복되는 경우 도움이되기를 바랍니다.


샘플 코드 :

Map<String,String> cache = new ConcurrentHashMap<String,String>(); 

key (Latitude + "_" + Longitude) and value (data) 

이 멀티 스레딩에 사용 cache 있음을 유의하십시오.

+0

아니면 목록을 정렬하고 시작하기 전에 중복을 제거하는 것이 좋습니다. – EJP

+0

@EJP 덕택에,'TreeMap'은'Latitude + Longitude'를 키로,'String'을 값으로 사용하는 것이 더 좋은 옵션이라고 생각합니다. – Braj

+0

'HashMap '은 어떨까요? – Braj