1

So, I have the following code:

try{
....
    if(serverResp.isSucces()){
      callbackListener.onDataLoaded(serverResp);
    }

 }catch(Exception e){
 //...do whatever I have to
}finally{
  urlConnection.disconnect();
}

My question is, when the urlConnection.disconnect is being called? Most of the examples with finally explains when its called in case of return. I understand that case, but here I don't have return but to call to a listener. In most cases the listener callback triggers a new Activity to start. I would like to be sure, that all my previous connections are closed down!

So the main question is:

  • When the finally get's called, if there is no return but listener callback?
  • Is this a proper way to close the urlConnection?
narancs
  • 5,234
  • 4
  • 41
  • 60

1 Answers1

0

finally is the best place to close resources.

The finally block is executed after the point in which the try/catch blocks are exited. This occurs when:

  1. The end of the try block is reached
  2. The try block is exited in any other way (break out of an outer loop, return, an uncaught exception is thrown, etc.)
  3. An exception is caught and execution reaches the end of the catch block
  4. The thread executing this code is terminated.

The only times that finally may not be executed are described here.

In your case, supposing no exceptions are thrown, your callback will be executed before the connection is closed. The connection will be closed after the callback is complete (via full execution or delegatation to some other thread).

Note that disconnect may only be a safe way to ensure connections are closed in newer version of Java. You would normally attempt to read the entire response and then close the input stream. You can find numerous discussions about this on this site.

Zircon
  • 4,677
  • 15
  • 32