HttpURLConnection的线程安全 [英] httpurlconnection thread safety

查看:1773
本文介绍了HttpURLConnection的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时的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后(<一href="http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Modules-sun/net/sun/net/www/protocol/http/HttpURLConnection.java.htm" rel="nofollow">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.

这篇关于HttpURLConnection的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆