Quantcast
Channel: Ajax Performance » java
Viewing all articles
Browse latest Browse all 2

java.net.URL considered annoying

$
0
0

The implementation of hashCode in java.net.URL has a quirk that tends to introduce subtle bugs into Java networking apps. Haven’t seen much discussion about this in the wild.

As implemented, hashCode uses the IP address of the URL hostname as part of its calculations. This leads to at least three annoying issues:

  1. Calling equals on a URL or using it as a key to a Map is a blocking operation on a network call. It’s unlikely this is what you intended, but it’s easy enough to overlook until (e.g.) your primary name server dies and you wonder why all hash lookups are now taking 5 seconds. This is how I stumbled onto the issue years ago.
  2. Calling equals on two URLs with identical paths and different hostnames will return true in the case that both hostnames map to the same IP. It can certainly be argued that this is intended behavior since the URLs point to the same network resource, but I’m guessing that most developers who call myURL.equals(yourURL) are expecting to get a string comparison, ala myURL.toString().equals(yourURL.toString())
  3. Using a URL as a key into a Map may lead to a miss in a DNS round robin scenario where the same hostname maps to multiple IPs. This is, I think, the most insidious case as most URLs will hash properly until one day you discover multiple entries in a Map keyed to string-identical URLs.

My advice? Simple enough. Just use strings. When working on projects involving URLs, a useful internal convention is to use all capitals to designate a method that will return a URL and lower case for a method that will return a String representation of the URL, perhaps suffixing with String just to be absolutely clear. Example:

public interface HttpRequest {
   public URL getURL();
   public String getUrlString();
}


Also, generic collections make spotting abuse of this convention much easier in the Map cases. Code that does HashMap<URL, HttpRequest> has a very distinct odor and is much easier to sniff out at the source.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images