为什么在这里使用 Atomic?
Why using Atomic here?
在阅读 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
只是被用于 return 来自回调的值,boolean[] found = new boolean[1];
也可以。
在阅读 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
只是被用于 return 来自回调的值,boolean[] found = new boolean[1];
也可以。