有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用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:

有人能向我解释一下为什么会发生这种情况,以及我如何处理它以使其发挥作用吗


共 (1) 个答案

  1. # 1 楼答案

    首先,请务必仔细阅读JMH的示例,使用这些配置(我可能每周通过JMH编写一次测试)很容易让自己陷入困境,但每次都会把事情搞砸

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

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