Kategorien
Java

Default timeouts for network connections in Java

You often find the answer to „How do I set default timeouts for (outgoing) network connectins in Java“ is

  1. System.setProperty("sun.net.client.defaultReadTimeout", "30000");
  2. System.setProperty("sun.net.client.defaultConnectTimeout", "30000");

But this may or may not work. Because, as stated by Sun in 2005:

Yes, it [the default timeout] is cached, or more precisely it is looked up only at startup time. This is by design.

Playing around with the code in the bug database entry linked to above and netcat, I found that it is also true for Java 6. Chances are high that it is true for Java 7, too.

What is meant by „startup time“ is using some network connection, e.g. HttpURLConnection. That means if there has some network connection been used before the properties are programmatically set, no network connections will use these timeout values!! If you set these properties in the JEE ContextListener or some startup-servlet they may have no impact anymore because your web container may already have used a network connection. Better use the commandline to pass these parameters.