apache httpclient multiple threads
When using Apache HttpClient in a multi-threaded environment, it is important to ensure thread safety. One way to achieve this is to use a separate instance of HttpClient
for each thread.
Here's an example that demonstrates how to use Apache HttpClient in a multi-threaded environment:
import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class HttpClientExample { public static void main(String[] args) throws Exception { String[] urls = {"http://www.example.com/", "http://www.google.com/", "http://www.yahoo.com/"}; ExecutorService executorService = Executors.newFixedThreadPool(urls.length); for (String url : urls) { executorService.execute(() -> { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine().getStatusCode()); } catch (IOException e) { e.printStackTrace(); } }); } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } }Sou:ecrwww.theitroad.com
In this example, we create a fixed thread pool with a size equal to the number of URLs we want to fetch. We then iterate over the URLs and submit a task to the thread pool for each URL.
In the task, we create a new instance of HttpClient
and execute an HttpGet
request to the given URL. We then print out the HTTP status code of the response.
Note that we use the ExecutorService.awaitTermination()
method to wait for all tasks to complete before shutting down the thread pool.
By creating a new instance of HttpClient
for each thread, we ensure that each thread has its own isolated HTTP client instance and avoid any potential concurrency issues.