问题描述
有一段时间,我一直在多线程环境中使用HttpClient。对于每个线程,当它启动连接时,它将创建一个全新的HttpClient实例。
For a while, I have been using HttpClient in a multithreaded environment. For every thread, when it initiates a connection, it will create a completely new HttpClient instance.
最近,我发现,通过使用这种方法,它可以导致用户打开太多端口,大多数连接处于TIME_WAIT状态。
Recently, I have discovered that, by using this approach, it can cause the user to have too many ports being opened, and most of the connections are in TIME_WAIT state.
因此,而不是每个线程在做:
Hence, instead of each thread doing :
HttpClient c = new HttpClient();
try {
c.executeMethod(method);
}
catch(...) {
}
finally {
method.releaseConnection();
}
我们计划:
[方法A]
// global_c is initialized once through
// HttpClient global_c = new HttpClient(new MultiThreadedHttpConnectionManager());
try {
global_c.executeMethod(method);
}
catch(...) {
}
finally {
method.releaseConnection();
}
在正常情况下,global_c将同时由50个++线程访问。我想知道,这会产生任何性能问题吗? MultiThreadedHttpConnectionManager是否使用无锁机制来实现其线程安全策略?
In a normal situation, global_c will be accessed by 50++ threads concurrently. I was wondering, will this create any performance issues? Is MultiThreadedHttpConnectionManager using a lock-free mechanism to implement its thread safe policy?
如果10个线程正在使用global_c,其他40个线程是否会被锁定?
If 10 threads are using global_c, will the other 40 threads be locked?
或者它会更好如果,在每个线程中,我创建一个HttpClient的实例,但显式释放连接管理器?
Or would it be better if, in every thread, I create an instance of an HttpClient, but release the connection manager explicitly?
[方法B]
MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManager();
HttpClient c = new HttpClient(connman);
try {
c.executeMethod(method);
}
catch(...) {
}
finally {
method.releaseConnection();
connman.shutdown();
}
connman.shutdown()是否会遇到性能问题?
Will connman.shutdown() suffer performance issues?
对于使用50 ++线程的应用程序,我可以知道哪种方法(A或B)更好吗?
May I know which method (A or B) is better, for application using an 50++ threads?
推荐答案
httpclient开发者社区推荐方法A.
Method A is recommended by httpclient developer community.
请参考了解更多详情。
这篇关于在多线程环境中使用HttpClient的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!