在阅读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];
会做一样好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句