Blog maintained by TechnoGems

Wednesday, August 25, 2010

Java URL connection timeout - default timeout might save you from hanging

Many times, when you make a url connection or any connection that works over tcp ip (ftp, http etc) protocol, it is possible that your client just hangs.  It is frustrating to debug this kind of issue because, you do not get any exception from your application except it just hangs.  This can be a problem especially in production environments where there are firewalls between every single component and it is hard to trace network traffic.   

If you are using sun jdk.1.4 or above there is a way you can prevent your code from just hanging.  Best of all, you do not even have to make a code change.  The sun jvm has a way to specify default timeout values for the net client.   All you have to do is just add the following java parameters to the command line that starts your application.  
-Dsun.net.client.defaultConnectTimeout=TimeoutInMiliSec -Dsun.net.client.defaultReadTimeout=TimeoutInMiliSec 
 
This will force the client to timeout and hopefully your application logs the exception that gives enough clue to debug the issue.   For more information about specifying network properties in java check out the Networking Properties guide from sun/oracle.

No comments: