使用并行流返回最快的提供值

时间:2015-10-06 11:15:39

标签: java multithreading parallel-processing java-8 java-stream

我有一组供应商,它们都有相同的结果,但速度不同(且不同)。

我想要一种优雅的方式同时启动供应商,并且只要其中一个产生了价值,就将其退回(丢弃其他结果)。

我已尝试使用并行流和Stream.findAny(),但它似乎总是阻止,直到所有结果都已生成。

这是一个证明我的问题的单元测试:

import org.junit.Test;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static org.junit.Assert.*;

public class RaceTest {

    @Test
    public void testRace() {
        // Set up suppliers
        Set<Supplier<String>> suppliers = Collections.newSetFromMap(new ConcurrentHashMap<>());
        suppliers.add(() -> "fast"); // This supplier returns immediately
        suppliers.add(() -> {
            try {
                Thread.sleep(10_000);
                return "slow";
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }); // This supplier takes 10 seconds to produce a value

        Stream<Supplier<String>> stream = suppliers.parallelStream();
        assertTrue(stream.isParallel()); // Stream can work in parallel
        long start = System.currentTimeMillis();
        Optional<String> winner = stream
                .map(Supplier::get)
                .findAny();
        long duration = System.currentTimeMillis() - start;
        assertTrue(winner.isPresent()); // Some value was produced
        assertEquals("fast", winner.get()); // The value is "fast"
        assertTrue(duration < 9_000); // The whole process took less than 9 seconds
    }
}

测试结果是最后一个断言失败,因为整个测试大约需要10秒才能完成。

我在这里做错了什么?

3 个答案:

答案 0 :(得分:11)

在这种情况下,最好使用Callable而不是Supplier(相同的功能签名)并使用自Java 5以来存在的良好的旧并发API:

Set<Callable<String>> suppliers=new HashSet<>();
suppliers.add(() -> "fast"); // This supplier returns immediately
suppliers.add(() -> {
        Thread.sleep(10_000);
        return "slow";
    }
);

ExecutorService es=Executors.newCachedThreadPool();
try {

    String result = es.invokeAny(suppliers);
    System.out.println(result);

} catch (InterruptedException|ExecutionException ex) {
    Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
es.shutdown();

注意,整个“全部运行并返回最快”的方式如何成为单个方法调用...

只要一个结果可用,它还有取消/中断所有待处理操作的好处,所以慢速操作实际上不会在这里等待整整十秒(好吧,在大多数情况下,因为时间不是确定性)。

答案 1 :(得分:3)

您目前使用的代码是不确定的。引用findAny()的Javadoc:

  

此操作的行为明确是不确定的;可以自由选择流中的任何元素。

您可以使用CompletionService并将所有任务提交给它。然后,CompletionService.take()将返回第一个已完成任务的Future

long start = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(suppliers.size());
CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
suppliers.forEach(s -> completionService.submit(() -> s.get()));
String winner = completionService.take().get();
long duration = System.currentTimeMillis() - start;
assertEquals("fast", winner); // The value is "fast"
assertTrue(duration < 9_000); // The whole process took less than 9 seconds

答案 2 :(得分:2)

Stream API不适合这样的事情,因为它不能保证任务完成时间。更好的解决方案是使用CompletableFuture

long start = System.currentTimeMillis();
String winner = CompletableFuture
        .anyOf(suppliers.stream().map(CompletableFuture::supplyAsync)
                .toArray(CompletableFuture[]::new)).join().toString();
long duration = System.currentTimeMillis() - start;
assertEquals("fast", winner); // The value is "fast"
assertTrue(duration < 9_000); // The whole process took less than 9 seconds

请注意,如果普通FJP没有足够的并行度,它仍然可能无法并行启动所有供应商。要解决此问题,您可以创建自己的池,该池具有所需的并行度级别:

long start = System.currentTimeMillis();
ForkJoinPool fjp = new ForkJoinPool(suppliers.size());
String winner = CompletableFuture
        .anyOf(suppliers.stream().map(s -> CompletableFuture.supplyAsync(s, fjp))
                .toArray(CompletableFuture[]::new)).join().toString();
long duration = System.currentTimeMillis() - start;
assertEquals("fast", winner); // The value is "fast"
assertTrue(duration < 9_000); // The whole process took less than 9 seconds
fjp.shutdownNow();