java - 为什么在这里使用 Atomic?
问题描述
在阅读 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];
也可以。
推荐阅读
- anylogic - 如何减少我使用的源块的数量?
- c# - 获取 Vuforia 目标图像旋转度数
- django - 如何根据当前用户是否是博客帖子的所有者来限制模板中显示的编辑链接?
- automation - 使用 JXA 向新联系人添加电子邮件
- android - Android Studio Emulator 目录已移除
- android - 如何在 Android Studio 中找到最新版本的 Kotlin
- ios - AppDelegate swfit4.2中的“applicationDidReceiveMemoryWarning”内存警告警报?
- c# - 将日期值 YYYY-MM-DD 从 excel 表导入 DataTable 仅获取最后一个值 DD
- r - 在汽车库中使用 scatterplotMatrix 时,右上角的绘图和左下角的绘图有什么区别?
- mongodb - 将日期转换为时间戳 mongodb