简体   繁体   中英

HashMap Iteration infinite loop

Set<Entry<String, Object>> entryset = full_map.entrySet();
Iterator<Entry<String, Object>> it = entryset.iterator();
while (it.hasNext()) {
    String key = (String) it.next().getKey();
    System.out.println(key);
    Object obj = full_map.get(key);
    JSONObject obj1 = (JSONObject) obj;
    URL url_2 = new URL("http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=" + obj1.getString("artist") + "&track="+obj1.getString("track") + "&limit=10&api_key=XYZ&format=json");
    System.out.println(url_2);
    URLConnection url_reader_2 = url_2.openConnection();
    BufferedReader reader_2 = new BufferedReader(new InputStreamReader((url_reader_2.getInputStream()), Charset.forName("UTF-8")));
    // System.out.println(reader_2);
    String iterator_2 = " ";
/*  while((iterator_2 = reader_2.readLine()) != null)
    {
        JSONObject jsonObject_2 = new JSONObject(iterator_2);
        System.out.println(jsonObject_2);
    }*/


}

The above code is generating an infinite loop. Any suggestions?? I have tried with the keySet() also instead of entrySet() , it gives the same result. Although if I remove:

BufferedReader reader_2 = new BufferedReader(new InputStreamReader(( url_reader_2.getInputStream()),Charset.forName("UTF-8")));

It doesn't go into the infinite loop.

This is certainly not an infinite loop case. More likely scenario is that your openInputStream action on urlConnection is taking very long and not timing out.

I don't think it is an infinite loop. There is no possibility for infinite loop, problem should be on URL connection or something, as you mentioned when you remove it, it is fine. Anyways you can log before and after the BufferedReader and also right after loop iteration to make sure problem is from this line or while loop.

I also think that this code is not a inifinite loop. Try to set following timeout parameter:

url_reader_2.setConnectTimeout(2000);

Moreover if there are a lot of hits on website then it can stuck with handling so many tcp connections

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM