java future 线程,正确实现Java Future多线程

In my servlet I am hitting several URL's to check their status and returning the response to user.

Hitting multipe requests takes lot of time: need threads and timouts. But i need my threads to geturn response : using Future for that reason.

My code outline:

ExecutorService executor = Executors.newFixedThreadPool(10);

Future future;

for (Map.Entry 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: Timeout OR "+e.getMessage());

}

}

executor.shutdownNow();

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.

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

Finally Updated my code (thanks to Sotirios Delimanolis and Kevin):

ExecutorService executor = Executors.newFixedThreadPool(20);

List> futures = new ArrayList>();

for (Map.Entry url : urls.entrySet())

{

Future future = executor.submit(new CallableRequestStatus(url.getValue()));

futures.add(future);

}

ArrayList results = new ArrayList();

statusModel status;

int i=0;

for (Map.Entry 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: 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> futures = new ArrayList<>();

for (Map.Entry url : urls.entrySet())

{

futures.add(executor.submit(new CallableRequestStatus(url.getValue())));

}

for (Future f : futures) {

results.add((statusModel) f.get(5, TimeUnit.SECONDS));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值