httpurlconnection thread safety

前端 未结 2 1281
北海茫月
北海茫月 2021-01-05 23:52

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 con

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-06 00:24

    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.

提交回复
热议问题