Best Practice to Use HttpClient in Multithreaded Environment

后端 未结 5 1851
猫巷女王i
猫巷女王i 2020-11-27 09:40

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 instan

5条回答
  •  余生分开走
    2020-11-27 10:33

    My reading of the docs is that HttpConnection itself is not treated as thread safe, and hence MultiThreadedHttpConnectionManager provides a reusable pool of HttpConnections, you have a single MultiThreadedHttpConnectionManager shared by all threads and initialised exactly once. So you need a couple of small refinements to option A.

    MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManag
    

    Then each thread should be using the sequence for every request, getting a conection from the pool and putting it back on completion of its work - using a finally block may be good. You should also code for the possibility that the pool has no available connections and process the timeout exception.

    HttpConnection connection = null
    try {
        connection = connman.getConnectionWithTimeout(
                            HostConfiguration hostConfiguration, long timeout) 
        // work
    } catch (/*etc*/) {/*etc*/} finally{
        if ( connection != null )
            connman.releaseConnection(connection);
    }
    

    As you are using a pool of connections you won't actually be closing the connections and so this should not hit the TIME_WAIT problem. This approach does assuume that each thread doesn't hang on to the connection for long. Note that conman itself is left open.

提交回复
热议问题