views:

57

answers:

2

Hi! I'm trying to connect to one URL that I know that exist but I don't know when. I don't have access to this server so I can't change anything to receive a event.

The actual code is this.

URL url = new URL(urlName);
for(int j = 0 ; j< POOLING && disconnected; j++){
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    int status = connection.getResponseCode();
    if(status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_NOT_MODIFIED){
        //Some work
    }else{
        //wait 3s
        Thread.sleep(3000);       
    }
}

Java not is my best skill and I'm not sure if this code is good from the point of view of performance. I'm opening a new connection every 3 seconds? or the connection is reused?

If I call to disconnect() I ensure that no new connections are open in the loop, but... it will impact in performance?.

Suggestions? What is the fast/best ways to know it a URL exist?

A: 

This code is okay from a performance point of view, it will create a new connection each time. Anyway if you have a Thread.sleep(3000) in your loop, you shouldn't have to worry about performance ;)

If you're concerned about connection usage on the server side, you can look into apache HTTP client, it has a lot of features. I think it handles keep alive connections by default.

Guillaume
I think he talks about performance from the point of using system resources. Using network is OS-specific and there may be all kinds of weird limitations (for example, I've had once a problem with windows not allowing me to open more than n socket connections in time t).
Nikita Rybak
The problem is with the resources of the other server. They said that we open more connections than expected. I'm not sure if this is the point of the code that cause this, by the openConnection() inside the loop.
Carlos Garces
@Carlos Garces You may try to use 'disconnect' and see if they complain again :) Or you may ask them to formulate limitations more clearly.
Nikita Rybak
A: 

1) Do use disconnect, you don't want numerous open connections you don't use. Discarding resources you don't use is a basic practice in any language.
2) I don't know if opening and closing new network connection every 3 seconds will pollute system resources, the only way to check it is to try.
3) You may want to watch for 'ConnectException', if by "URL [does not] exist" you mean server is down.

Nikita Rybak
"URL [does not] exist" means that the URL return a 404. But is temporal.. It'll exist, the URL is created on demand by other process.
Carlos Garces