httpurlconnection thread safety

前端 未结 2 1282
北海茫月
北海茫月 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条回答
  •  猫巷女王i
    2021-01-06 00:42

    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.

提交回复
热议问题