如何在GPars的给定超时内获得多个异步结果?

时间:2016-10-20 21:07:49

标签: multithreading groovy parallel-processing java-8 gpars

我想要检索多个"昂贵的"使用并行处理但在特定超时内的结果。

我正在使用GPars Dataflow.task但看起来我错过了一些东西,因为只有当所有数据流变量都被绑定时,进程才会返回。

def timeout = 500
def mapResults = []
GParsPool.withPool(3) { 
    def taskWeb1 = Dataflow.task {
        mapResults.web1 = new URL('http://web1.com').getText()
    }.join(timeout, TimeUnit.MILLISECONDS)
    def taskWeb2 = Dataflow.task {
        mapResults.web2 = new URL('http://web2.com').getText()
    }.join(timeout, TimeUnit.MILLISECONDS)
    def taskWeb3 = Dataflow.task {
        mapResults.web3 = new URL('http://web3.com').getText()
    }.join(timeout, TimeUnit.MILLISECONDS)
}

我确实在GPars Timeouts doc中看到了一种使用Select来获得超时内最快结果的方法。 但我正在寻找一种在给定时间范围内尽可能多地检索结果的方法。

是否有更好的" GPars"实现这个的方法? 或者使用Java 8 Future / Callable?

1 个答案:

答案 0 :(得分:0)

由于您对基于Java 8的解决方案也很感兴趣,这是一种方法:

int timeout = 250;
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
    Map<String, CompletableFuture<String>> map = 
        Stream.of("http://google.com", "http://yahoo.com", "http://bing.com")
            .collect(
                Collectors.toMap(
                    // the key will be the URL
                    Function.identity(),
                    // the value will be the CompletableFuture text fetched from the url
                    (url) -> CompletableFuture.supplyAsync(
                        () -> readUrl(url, timeout), 
                        executorService
                    )
                )
            );
    executorService.awaitTermination(timeout, TimeUnit.MILLISECONDS);

    //print the resulting map, cutting the text at 100 chars
    map.entrySet().stream().forEach(entry -> {
        CompletableFuture<String> future = entry.getValue();
        boolean completed = future.isDone() 
                && !future.isCompletedExceptionally() 
                && !future.isCancelled(); 
        System.out.printf("url %s completed: %s, error: %s, result: %.100s\n",
            entry.getKey(),
            completed, 
            future.isCompletedExceptionally(),
            completed ? future.getNow(null) : null);
    });
} catch (InterruptedException e) {
    //rethrow
} finally {
    executorService.shutdownNow();
}

这将为您提供尽可能多的Future个URL,但您可以查看是否有任何任务因异常而失败。如果您对这些异常不感兴趣,只需要成功检索的内容就可以简化代码:

int timeout = 250;
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
    Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
    Stream.of("http://google.com", "http://yahoo.com", "http://bing.com")
        .forEach(url -> {
            CompletableFuture
                .supplyAsync(
                    () -> readUrl(url, timeout), 
                    executorService
                ).thenAccept(content -> map.put(url, content));
        });
    executorService.awaitTermination(timeout, TimeUnit.MILLISECONDS);

    //print the resulting map, cutting the text at 100 chars
    map.entrySet().stream().forEach(entry -> {
        System.out.printf("url %s completed, result: %.100s\n",
            entry.getKey(), entry.getValue() );
    });
} catch (InterruptedException e) {
    //rethrow
} finally {
    executorService.shutdownNow();
}

在打印结果之前,这两个代码将等待大约250毫秒(由于向执行程序服务提交任务,因此只需要一点点)。我发现大约250毫秒是一些阈值,其中一些url-s可以在我的网络上获取,但不一定全部。随意调整超时以进行实验。

对于readUrl(url, timeout)方法,您可以使用像Apache Commons IO这样的实用程序库。即使您没有明确考虑timeout参数,提交给执行程序服务的任务也会收到中断信号。我可以为此提供一个实现,但我认为它超出了你问题中主要问题的范围。