notnoop
notnoop

Reputation: 59307

HTTPS requests and multi-threading

Is Java's URL class a thread-safe, in particular [URL.openConnection()](http://java.sun.com/javase/6/docs/api/java/net/URL.html#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.

Upvotes: 3

Views: 3093

Answers (3)

ZZ Coder
ZZ Coder

Reputation: 75496

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.

Upvotes: 3

Keith Randall
Keith Randall

Reputation: 23265

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.

Upvotes: 0

Suppressingfire
Suppressingfire

Reputation: 3286

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.

Upvotes: 4

Related Questions