gpt4 book ai didi

java - getClass().getName() 返回 null

转载 作者:行者123 更新时间:2023-12-02 05:06:55 24 4
gpt4 key购买 nike

我正在使用 testNG 为我们的测试编写者提供一个“框架”,以加快测试的开发速度。为了实现这一目标,我有一个抽象的 Test 类。所有的书面测试都源自这个 Test 类。这些测试可以通过 testNG 并行运行。现在我注意到,有时在 @BeforeClass 方法中,我的简单“getClass().getName()”方法在并行执行时会返回 null。

private static ThreadLocal<String> className;

@BeforeClass
public void init(){
initName();
className.set(getClass().getName());
log("Starting test " + className.get());
}

private synchronized void initName(){
if(className == null){
className = new ThreadLocal<>();
}
}

当我并行运行一系列测试时,我得到以下输出:

...
Starting test com.mycompany.testsets.LocalTestSet$IntegrationTest3
Starting test null
Starting test com.mycompany.testsets.LocalTestSet$IntegrationTest1
...

一些备注:
Threadlocal ClassName 必须是静态的(我稍后在 @Dataprovider 中使用它的值)
由于它是随机发生的并且可能发生在任何测试中,因此我认为这是一个线程安全问题,但我不知道如何使“getClass().getName()”更加线程安全。

感谢您的帮助

最佳答案

您似乎存在竞争状况。如果一个线程在另一个线程调用 log 之前调用 initName,则新的 ThreadLocal 将没有值,即。将返回null

这里没有线程安全来保护 initName 中的 null 检查。

关于java - getClass().getName() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27706281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com