Reputation: 65
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
Upvotes: 2
Views: 1192
Reputation: 4715
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)
Upvotes: 1
Reputation: 20323
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));
}
Upvotes: 1