Monday, March 25, 2013

Connection Timeouts

Just noticed that the app has a number of connection Timeouts which caused the app to continue waiting on a response from a dead connection. This mean that the app would essentially wait forever for a connection that has already - less than ideal, needless to say.

Researching, I found that I can define a boolean value when opening the connection which should essentially throw an Exception when the timeout reached with no response from server. 
HttpConnection http = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
Again with the monkey design in Java, the parameter list does not take a time parameter hence, I cannot manually define the timeout myself. Instead, I have to wait for a system-dependent timeout that no-one seems to know the real value of(ranging from 60 secs to 5 mins-depending on who you ask). I tested this and did not get any Exception thrown even though the app lost connection for quite sometime(situ 15 mins).

Bit the bullet on that and approached the problem from another angle. I create a timertask which after a period x will check to see if the connection has been read(using a boolean flag) and if not, try and close the connection. I then have it throw a custom Exception which I wanted to catch in the main app so that I can know that the connection timed out and handle accordingly.

connectionTimeOut = true;
       
        final Timer timer = new Timer();
        TimerTask timeoutTask = new TimerTask(){
            public void run(){System.out.println("Timeout Expired:");
       
                //Shutdown streams
                try {
                    if(connectionTimeOut){
                        if(is != null){
                            //Close all streams
                           is.close();
                        }
                        timer.cancel(); //Shutdown timer
                        System.out.println("Timing out..");                      
                        //Throw exception to be handled in main class
                      kill = true;
                        throw new TimeoutException("Connection Timed Out!");
                    }
                } catch (TimeoutException ex) {
                    ex.printStackTrace();
                }  catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        };
        timer.schedule(timeoutTask, 3000);
        

Unfortunately, timerTask inherits from Thread which means that there's no way to catch the thrown Exception outside it's own thread(and hence the calling method). So in essence, am stuck with a half-baked thread which cleans up pending open connections after the timeout but which cannot communicate back to the original calling Thread(and hence method) to notify it of the action.

P/S: Am still thinking some more on how to solve this problem. :(

No comments:

Post a Comment