运行 使用可完成未来的方法基准

Run benchmark on method using completable future

我正在尝试衡量特定方法的性能。 我 运行 直接调用方法时,基准测试很好, 但是当该方法使用自定义执行程序的可完成未来时,一切都崩溃了。我已经实现了使用可完成未来的方法,以便在该方法花费太长时间时强制超时。

@Benchmark
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Threads(value = 5)
@Warmup(iterations = 20)
@Measurement(iterations = 50, timeUnit = TimeUnit.MILLISECONDS)
public String very_big_query(TestState testState) throws Exception {
    return testState.transpiler.process(testState.veryBigQuery);
}

@State(Scope.Thread)
public static class TestState {
    String veryBigQuery;
    Transpiler transpiler;

    @Setup(Level.Trial)
    public void doSetupTrial() throws Exception {
        veryBigQuery = "(";
        for(int i = 0; i < 99; i++) {
            veryBigQuery += String.format("java_%s OR ", i);
        }
        veryBigQuery += "java_100) AND (";
        for(int i = 100; i < 199; i++) {
            veryBigQuery += String.format("java_%s OR ", i);
        }
        veryBigQuery += String.format("java_%s)", 200);
    }

    @Setup(Level.Invocation)
    public void doSetupInvocation() throws Exception {
        random = ThreadLocalRandom.current().nextInt(0, productionQueries.size());
        randomQuery = productionQueries.get(random);
        transpiler = new Transpiler(5, 100); //number of threads in custom pool for the executor, timeout in milliseconds
    }
}

public String process(final String input) throws Exception {
    CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
        return SOME_STRING;
    }, executor);

    return cf.get(timeoutInMillis, TimeUnit.MILLISECONDS);
}

this.executor = Executors.newFixedThreadPool(numberOfThreads);

我收到这个错误

JMH had finished, but forked VM did not exit, are there stray running threads? Waiting 24 seconds more...

Non-finished threads:

有人可以向我解释为什么会发生这种情况吗?我该如何处理它才能使其发挥作用?

首先一定要通读 JMH 的示例,使用这些配置很容易搬起石头砸自己的脚(我可能每周通过 JMH 编写一次测试)并且每次都会把事情搞砸时间。

然后,去掉 Level.Invocation 除非你真的理解它的作用...

最后可以在@TearDown方法中关闭执行器。