Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httpurlconnection thread safety

Is HttpUrlConnection thread safe? I.e. if I have an HttpConnection instance connected to a server and this instance is used by different threads (e.g.try to send a POST concurrently) how will this situation be handled by HttpUrlConnection? a) Will they send the POSTs serially, or b) the first thread sends the POST, gets the response and then the second thread will send the POST? If they send the POSTs serially, this means multiple active POSTs to the same tcp connection. Is this allowed? Can it be handled by a server?

Thanks

like image 577
Cratylus Avatar asked Jul 17 '10 18:07

Cratylus


2 Answers

it's not thread safe.

you shouldn't cache/share a connection. just create a new connection for each request. there is certainly a little overhead in creating new connections, but it is very small, you shouldn't worry about it.

the spirit of HTTP is actually connection-less. there is no, semantically speaking, connection between client and server. client sends a request, server sends back a response, that is all.

although today HTTP is indeed defined on top of TCP, which is a connection-ful protocol, and HTTP may use long lived TCP connection for multiple requests/responses, that's not the nature of HTTP.

since a request-response exchanged can be implemented on top of most network protocols, originally HTTP allowed possibility of specifying underlying protocols. We can imagine http request/response exchange over email - http:/smtp/www.example.com; maybe RMI - http:/rmi/www.example.com; the default is TCP, so http:// really means http:/tcp/

today, only TCP is used, and we are left with this curious double slash separator. but it's a reminder that HTTP's dependency on TCP is rather incidental.

like image 59
irreputable Avatar answered Nov 15 '22 01:11

irreputable


It does not say if it is or not in the docs. After looking at the code ( http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Modules-sun/net/sun/net/www/protocol/http/HttpURLConnection.java.htm ) it looks like getInputStream and getOutputStream are synchronized. The concern I do have is that if you have a Thread that gets an input Stream and at the same time you have another Thread that gets an Output Stream you might get your signals crossed. inputStream and outputStream are instance variables that probably should not be shared across Threads.

If I were you I would implement a queue that would allow you to post the messages to the queue and would then post them to the server one at a time. When the request returns then you simply invoke a callback. This would make sure that a request was not sent before a response came back.

like image 37
Romain Hippeau Avatar answered Nov 15 '22 01:11

Romain Hippeau