Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Threading httpClient

public class test {
    public static final int nThreads = 2;

    public static void main(String[] args) throws ExecutionException, InterruptedException{
    //  Runnable myrunnable = new myRunnable();
        ExecutorService execute = Executors.newFixedThreadPool(nThreads);

        for (int i = 0; i < nThreads; ++i) {
            execute.execute(new MyTask());
        }           

        execute.awaitTermination(1000, TimeUnit.MILLISECONDS);

        execute.shutdown();
    }
}

class MyTask implements Runnable {
    public static final int maxCalls = 10;
    public static final int sleepMillis = 500;
    private static HttpResponse response;
    private static HttpClient httpclient;

    public void run(){
        int counter = 0;

        while (true) {

            if (counter >= maxCalls) {
                break;
            }
            try {
                Thread.currentThread().sleep(sleepMillis);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            execHttpRequest();

            ++counter;
        }
    }

    private void execHttpRequest() {
        httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("My URL");

        try {

            response = httpclient.execute(httpget);
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String output;
            while((output=br.readLine())!=null){
                System.out.println(Thread.currentThread().getName() +output);
            }
            br.close();

            httpclient.getConnectionManager().shutdown();
            //httpclient.getConnectionManager().shutdown();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{

            httpclient.getConnectionManager().shutdown();
        }

    }


}

While running this code, I get the following exception:

Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.SingleClientConnManager.getConnection(SingleClientConnManager.java:216)
    at org.apache.http.impl.conn.SingleClientConnManager$1.getConnection(SingleClientConnManager.java:190)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:401)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at MyTask.execHttpRequest(test.java:72)
    at MyTask.run(test.java:60)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
java.io.InterruptedIOException: Connection has been shut down
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:543)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at MyTask.execHttpRequest(test.java:72)
    at MyTask.run(test.java:60)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.apache.http.impl.conn.ConnectionShutdownException
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.assertValid(AbstractPooledConnAdapter.java:86)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.getRoute(AbstractPooledConnAdapter.java:112)
    at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:740)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:577)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
    ... 8 more

When I execute http request, then I see these Exceptions. It works perfectly fine for single-threaded. I am trying to call a specific URL (which works perfectly fine) but when I add more than one thread to it, it throws an illegal state exception.

like image 658
RFT Avatar asked Nov 15 '11 14:11

RFT


People also ask

Is HttpClient multithreaded?

HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.

What is the difference between HttpClient and CloseableHttpClient?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated. The HttpClient is an interface for this class and other classes. You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder .

Is Java 11 HttpClient thread-safe?

Once created, an HttpClient instance is immutable, thus automatically thread-safe, and you can send multiple requests with it. By default, the client tries to open an HTTP/2 connection. If the server answers with HTTP/1.1, the client automatically falls back to this version.

Is node js support multithreading?

However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.


1 Answers

Came here to say, MultiThreadedHttpConnectionManager is outdated. Currently (HttpClient version 4.*) this is the way: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e639

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
        new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);
like image 121
bpgergo Avatar answered Sep 25 '22 16:09

bpgergo