gpt4 book ai didi

java - 为什么在这里使用 Atomic?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:18 25 4
gpt4 key购买 nike

在阅读 SpringRetry 的源代码时,我遇到了这段代码:

private static class AnnotationMethodsResolver {

private Class<? extends Annotation> annotationType;

public AnnotationMethodsResolver(Class<? extends Annotation> annotationType) {
this.annotationType = annotationType;
}

public boolean hasAnnotatedMethods(Class<?> clazz) {
final AtomicBoolean found = new AtomicBoolean(false);
ReflectionUtils.doWithMethods(clazz,
new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException,
IllegalAccessException {
if (found.get()) {
return;
}
Annotation annotation = AnnotationUtils.findAnnotation(method,
annotationType);
if (annotation != null) { found.set(true); }
}
});
return found.get();
}

}

我的问题是,为什么在这里使用 AtomicBoolean 作为局部变量?我检查了 RelfectionUtils.doWithMethods() 的源代码,没有发现任何并发调用。

最佳答案

hasAnnotatedMethods 的每次调用都会得到它自己的 found 实例,因此调用 hasAnnotatedMethods 的上下文无关紧要。

可能ReflectionUtils.doWithMethods 从多个线程调用doWith 方法,这将需要doWith是线程安全的。

我怀疑 AtomicBoolean 只是被用来从回调中返回一个值,而 boolean[] found = new boolean[1]; 会做同样的事情好吧。

关于java - 为什么在这里使用 Atomic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014266/

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