HttpURLConnection的线程安全线程、安全、HttpURLConnection

2023-09-04 00:35:22 作者:彩虹上的小猫咪

时的HttpURLConnection线程安全的?即如果我有连接到服务器的HttpConnection的实例,该实例使用不同的线程(egtry发送POST兼)如何将这一情况被HttpURLConnection的处理?一)将他们送岗位连续,或b)第一个线程发送POST,获取响应,然后第二个线程将发送POST?如果他们发送的职位顺序,这意味着多个活动职位,以相同的T​​CP连接。这可以吗?它可以通过一台服务器来处理?

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?

感谢

推荐答案

这并不是说,如果它是与否的文档。着眼于code后(http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Modules-sun/net/sun/net/www/protocol/http/HttpURLConnection.java.htm )它看起来像的getInputStream和getOutputStream方法是同步的。我有令人担忧的是,如果你有一个线程获得一个输入流,并在同一时间,你有另一个线程得到一个输出流,你可能会得到你的信号交叉。 InputStream和OutputStream是可能不应该在线程间共享的实例变量。

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.