首页 > 解决方案 > 为什么在这里使用 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()但没有找到任何并发调用。

标签: javaspringjava.util.concurrent

解决方案


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

可以从多个线程调用该方法这需要线程安全。ReflectionUtils.doWithMethodsdoWithdoWith

我怀疑它AtomicBoolean只是被用来从回调中返回一个值,这boolean[] found = new boolean[1];也可以。


推荐阅读