views:

78

answers:

3

Is Java's URL class a thread-safe, in particular URL.openConnection()?

In my application, I make tens of concurrent HTTPS connections a second to the same URL, and I would like to maximize object reuse. Yet, it's not clear from the documentation what can be reused.

EDIT: I'm open to using a different library if needed.

+2  A: 

My standard response about HTTP and java is to recommend Apache HttpClient. It supports HTTP 1.1, so you can keep those connections open for reuse after you've had a successful HTTP request/response with the server.

It has built-in support for connection pooling and the documentation describes how to use it in a multithreaded context.

Suppressingfire
+1 for the multithreaded HttpClient choice. You'll save a lot of hairpulling.
Benjamin Cox
A: 

URL.openConnection will make a HttpsURLConnection object, which is a subclass of HttpURLConnection. The docs for HttpURLConnection state that it may use a single underlying connection to the server to statisfy multiple requests. I'm assuming this is sharing ala HTTP 1.1.

So you will get a new HttpsURLConnection object with each URL.openConnection call, but you won't get lots of network connections.

Keith Randall
Yes, but can two threads call `URL.openConnection()` safely?
notnoop
+1  A: 

Yes. It's thread-safe. I use it in many threads and haven't found any issues.

The Sun's default handler also supports keep-alive by default so multiple threads may share the same connection. You have to be careful to read all responses (including ErrorStream). Otherwise, the next request will start in a bad state.

ZZ Coder