简体   繁体   English

不打电话获得期货清单

[英]Not calling get on list of futures

I'm using a global Executor service with some fixed thread pool size. 我正在使用具有某些固定线程池大小的全局Executor服务。 We have bunch of related tasks that we submit for execution and wait on list of futures. 我们有一堆相关的任务,我们提交执行并等待期货清单。

Recently, we faced a high CPU utilization issue and on debugging I found that an exception occurred while calling get() on one of the item in list of futures. 最近,我们面临CPU使用率高的问题,在调试时,我发现对期货列表中的某一项调用get()时发生了异常。 Current, we iterate over the list and there is a try catch surrounding the whole loop. 当前,我们遍历列表,整个循环周围有一个try catch。

try{
    List<Result> results = new ArrayList<>()
    for(Future<Result> futureResult: futureResults{
        Result result = futureResult.get();
        results.add(result);
    }
} catch(Exception e){
  throw new InternalServiceException(e);
}

//Do something with results

Wanted to know the behaviour of other threads if get is never called on some of the items in future. 想知道其他线程的行为,如果将来永远不会在某些项目上调用get的话。 I tried searching but was not able to find anything. 我尝试搜索,但找不到任何东西。

Also, can this behaviour trigger high CPU utilization ? 此外,这种行为是否会触发较高的CPU使用率?

http://www.journaldev.com/1650/java-futuretask-example-program http://www.journaldev.com/1650/java-futuretask-example-program

I would still check if the future isDone as in the example above. 我仍将按照上面的示例检查future isDone。

If you need to run other operations or want to utilize the CPU better then I would put the collector in a separate thread and perhaps just poll for results every minute or so. 如果您需要运行其他操作或想更好地利用CPU,则可以将收集器放在单独的线程中,也许每分钟左右轮询一次结果。

Could be scheduled or handled by Thread.sleep. 可以由Thread.sleep计划或处理。

Executors class provides various methods to execute Callable in a thread pool. Executors类提供了各种方法来在线程池中执行Callable。 Since callable tasks run in parallel, we have to wait for the returned Object. 由于可调用任务并行运行,因此我们必须等待返回的Object。

Callable tasks return java.util.concurrent.Future object. 可调用任务返回java.util.concurrent.Future对象。 Using Future we can find out the status of the Callable task and get the returned Object. 使用Future,我们可以找出Callable任务的状态并获取返回的Object。

It provides get() method that can wait for the Callable to finish and then return the result. 它提供了get()方法,可以等待Callable完成,然后返回结果。

There is an overloaded version of get() method where we can specify the time to wait for the result, it's useful to avoid current thread getting blocked for longer time. 有一个get()方法的重载版本,我们可以在其中指定等待结果的时间,这对于避免当前线程阻塞更长的时间很有用。

Future provides cancel() method to cancel the associated Callable task. Future提供了cancel()方法来取消关联的Callable任务。 There are isDone() and isCancelled() methods to find out the current status of associated Callable task. 有isDone()和isCancelled()方法来查找关联的Callable任务的当前状态。

Here is a simple example of Callable task that returns the name of thread executing the task after some random time. 这是Callable任务的一个简单示例,该示例在一段时间后返回执行该任务的线程的名称。 We are using Executor framework to execute 10 tasks in parallel and use Future to get the result of the submitted tasks. 我们正在使用Executor框架并行执行10个任务,并使用Future获取已提交任务的结果。

public class FutureObjectTest implements Callable<String>{

    @Override
    public String call() throws Exception {
        long waitTime = (long) (Math.random()*10000);
        System.out.println(Thread.currentThread().getName() + " waiting time in MILISECONDS " + waitTime);
        Thread.sleep(waitTime);
        return Thread.currentThread().getName() + " exiting call method.";
    }

    public static void main(String [] args){
        List<Future<String>> futureObjectList = new ArrayList<Future<String>>();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Callable<String> futureObjectTest = new FutureObjectTest();
        for(int i=0; i<10; i++){
            Future<String> futureResult = executorService.submit(futureObjectTest);
            futureObjectList.add(futureResult);
        }
        for(Future<String> futureObj : futureObjectList){
            try {
                System.out.println(futureObj.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Starting get method of wait");
        ////////////get(Timeout) method///////
        futureObjectList.clear();
        for(int i=0; i<10; i++){
            Future<String> futureResult = executorService.submit(futureObjectTest);
            futureObjectList.add(futureResult);
        }
        executorService.shutdown();
        for(Future<String> futureObj : futureObjectList){
            try {
                System.out.println(futureObj.get(2000,TimeUnit.MILLISECONDS));
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM