【发布时间】:2018-04-24 19:37:29
【问题描述】:
我想遍历异步函数的搜索空间。我将逻辑编码如下:
/**
* Assuming that a function maps a range of inputs to the same output value, minimizes the input value while
* maintaining the output value.
*
* @param previousInput the last input known to return {@code target}
* @param currentInput the new input value to evaluate
* @param function maps an input to an output value
* @param target the expected output value
* @return the minimum input value that results in the {@code target} output value
* <br>{@code @throws NullPointerException} if any argument is null
* <br>{@code @throws IllegalArgumentException} if {@code stepSize} is zero}
*/
private static CompletionStage<BigDecimal> optimizeInput(BigDecimal previousInput,
BigDecimal currentInput,
BigDecimal stepSize,
Function<BigDecimal, CompletionStage<BigDecimal>> function,
BigDecimal target)
{
return function.apply(currentInput).thenCompose(output ->
{
assertThat("stepSize", stepSize).isNotZero();
int outputMinusTarget = output.compareTo(target);
if (outputMinusTarget != 0)
return CompletableFuture.completedFuture(previousInput);
BigDecimal nextInput = currentInput.add(stepSize);
if (nextInput.compareTo(BigDecimal.ZERO) < 0)
return CompletableFuture.completedFuture(previousInput);
return optimizeInput(currentInput, nextInput, stepSize, function, target);
});
}
不幸的是,如果函数的搜索空间很大,这会在一些迭代后引发 StackoverflowError。是否可以使用固定大小的堆栈迭代遍历搜索空间?
【问题讨论】:
-
你的
function真的是异步的吗?否则这会使optimizeInput()成为一个简单的递归方法。此外,您似乎没有对这段代码中的任何内容进行并行化,所以如果不使用CompletableFuture来实现它不是更简单(也许只是将初始调用包装在supplyAsync()中)。最好提供一个示例function和相应的堆栈跟踪。 -
@DidierL
function可以是同步的或异步的。不同的调用者传入不同类型的函数。代码不提前知道,但它需要在没有StackoverflowError的情况下处理这两种情况。
标签: java java-8 stack-overflow completable-future