2

I want my application to timeout in some specific seconds, but it keeps on trying to contact the specified URL until it gets a response. Below is the code I am using.

System.getProperties().setProperty("sun.net.client.defaultConnectTimeout", timeOut); System.getProperties().setProperty("sun.net.client.defaultReadTimeout", timeOut); URL url = new URL(targetURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

but if I set following property

connection.setConnectTimeout(Integer.parseInt(timeout)); 

then it gets timed out in desired time without waiting for server's response.

So, why doesn't it get timed out by using just the system properties?

Edit: Does it have anything to do with this behavior/bug? Or is there any relation with Java version, because the same code used to work in Java 1.4 but now I am using Java 1.7.

1
  • @brso05 Can you suggest something? Commented Dec 16, 2016 at 7:56

1 Answer 1

4

A standard approach to object-oriented design is defensive copying. This means that methods return copies of their data, rather than returning the actual internal object itself, so other code cannot attempt to perform harmful actions without going through the API from which it obtained the object, so the changes can be checked for validity.

System.getProperties() returns a Properties object which is a copy of the internal system properties. Use System.setProperty instead.

Sign up to request clarification or add additional context in comments.

5 Comments

You are correct about the "defensive copying" thing but it's not working with the changes you suggested though.
What is the actual value of timeOut?
40000 milliseconds
Are you certain the string value of timeOut is "40000"? No spaces, no punctuation?
I am quite sure, because it is working fine with 'connection.setConnectTimeout(Integer.parseInt(timeout));'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.