How to use the threads of a thread pool for each http query in Java?

advertisements

I need to create a thread pool of a fixed size and use the thread for every http request. Can anyone specify how to do this?

Thanks in advance

The code is

    HttpGet httpGet = new HttpGet(url);
    HttpClient  httpClient =  new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpGet);
    return httpResponse;

Here i need to use the thread from thread pool for every httpresponse


You can use Executors and pass your own Runnable which will process your httpResponse. Code snippet:

public class MyHttpResponseHandler implements Runnable {

    private HttpResponse httpResponse = null;

    public MyHttpResponseHandler(HttpResponse httpResponse){
        this.httpResponse = httpResponse;
    }
    @Override
    public void run() {
        //Do something with the httpResponse
    }
}

void processHttpResponse(){
    HttpGet httpGet = new HttpGet(url);
    HttpClient  httpClient =  new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpGet);
    ExecutorService executor = Executors.newFixedThreadPool(10);
    executor.execute(new MyHttpResponseHandler(httpResponse));
}