Search code examples
javahttpthread-sleep

Stop current thread & wait for HTTP connection


I am running some logic in a Thread that depends on a HTTP connection to a remote server. Currently, the thread crashes, if the remote server is not running. I want to modify the logic so that the thread waits for the remote server to become available again.

Technically, the solution seems strait forward. Something along the lines of:

                boolean reconnect = false;

                while (!reconnect) {
                    try {
                        URL url = new URL("my.remoteserver.com");
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.connect();
                        reconnect = true;
                    } catch (Exception ex) {
                        // wait a little, since remote server seems still down
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e1) {
                            // if thread was interrupted while waiting then terminate thread
                            break;
                        }
                    }
                }

However, this solution is not very elegant. Also, the use case seems so generic that I suspect this could be done by some helpful library. Alas, I could not find any - who can tell me how to improve my solution?


Solution

  • I think this use case is simple enough to implement yourself instead of introducing additional dependencies. If you are concerned about your solution not being very elegant I suggest refactoring it into a couple of smaller methods, for example like this:

    public void connect() {
        try {
            connectWithRetries();
        } catch (InterruptedException e) {
            // Continue execution
        }
    }
    
    private void connectWithRetries() throws InterruptedException {
        while (!tryConnect()) {
            sleep();
        }
    }
    
    private boolean tryConnect() {
        try {
            URL url = new URL("my.remoteserver.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    
    private void sleep() throws InterruptedException {
        Thread.sleep(5000);
    }