问题描述
在我的servlet中,我要敲击几个URL来检查它们的状态并将响应返回给用户.
In my servlet I am hitting several URL's to check their status and returning the response to user.
命中多倍请求需要很多时间:需要线程和timouts.但是我需要我的线程来响应:出于这个原因使用Future.
Hitting multipe requests takes lot of time: need threads and timouts. But i need my threads to geturn response : using Future for that reason.
我的代码概述:
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<statusModel> future;
for (Map.Entry<String, String> url : urls.entrySet())
{
try
{
future = executor.submit(new CallableRequestStatus(url.getValue()));
status = (statusModel) future.get(5, TimeUnit.SECONDS);
results.add(status);
}
catch (InterruptedException | ExecutionException | TimeoutException e)
{
System.out.println("Error<checkServers>: Timeout OR "+e.getMessage());
}
}
executor.shutdownNow();
可调用类的所有结果都进入状态对象,然后我将其添加到数组列表中.我的问题是我的方法阻止了我同时运行所有10个线程.我必须等待5秒钟才能获取状态对象,然后再移至下一个URL.
All the results from my callable class is coming in status object which I later add to an arraylist.My problem here is that my approach is blocking me from running all 10 threads at same time. I have to wait 5 secs for getting my status object and then move to next URL.
我认为我的方法是错误的.我尝试在线查找,但找不到任何涉及自定义对象和Arraylist的示例.
I am thinking my approach is faulty. I tried looking online but I couldnt find any example with custom objects and Arraylist involved.
任何人都可以帮助我纠正我的错误.预先感谢
Can anyone help me correct my fault.Thanks in advance
最后更新了我的代码(感谢Sotirios Delimanolis和Kevin):
Finally Updated my code (thanks to Sotirios Delimanolis and Kevin):
ExecutorService executor = Executors.newFixedThreadPool(20);
List<Future<statusModel>> futures = new ArrayList<Future<statusModel>>();
for (Map.Entry<String, String> url : urls.entrySet())
{
Future<statusModel> future = executor.submit(new CallableRequestStatus(url.getValue()));
futures.add(future);
}
ArrayList<statusModel> results = new ArrayList<statusModel>();
statusModel status;
int i=0;
for (Map.Entry<String, String> url : urls.entrySet())
{
try
{
status = (statusModel) futures.get(i).get(500, TimeUnit.MILLISECONDS);
// do some stuff with status and
if(status.getStatusCode()/100 == 2)
results.add(status);
}
catch (InterruptedException | ExecutionException | TimeoutException e)
{
System.out.println("Error<checkServers>: Timeout OR "+e.getMessage());
}
i++;
}
executor.shutdownNow();
System.out.println("Shutdown: "+executor.isShutdown());
希望它对某人有帮助:)
Hope its helpful for someone :)
推荐答案
您需要先提交所有内容,然后分别等待.如下所示,为清楚起见,删除了异常处理:
You need to submit everything upfront, then wait separately. As below, exception handling removed for clarity:
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Future<statusModel>> futures = new ArrayList<>();
for (Map.Entry<String, String> url : urls.entrySet())
{
futures.add(executor.submit(new CallableRequestStatus(url.getValue())));
}
for (Future<statusModel> f : futures) {
results.add((statusModel) f.get(5, TimeUnit.SECONDS));
}
这篇关于正确实现Java Future多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!