How to use the threads from a thread pool for every httprequest in java?

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

Answers


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));
}

You should probably create a FixedThreadExecutor http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)

then create a Runnable tasks http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html

and run them in the executor via sumbit() or executeAll() function http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

Maybe you shoudl do the HttPRequest in the thread also. And mark this as an homework (it smells like one)


Need Your Help

MySQL select given number of rows and always select all rows within the same day

mysql sql date datetime

I want to do a MySQL Query which selects a given number of Rows from a single table from a given offset like

why does the memory my program uses keep growing as it runs?

c++ memory 2d sdl game-engine

From first searching about this I found some sources saying i probably have a memory leak. But when i searched into detail about what a memory leak is, it said i happens when i use "new" and dont use

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.