为什么使用原子在这里?

raging_sweet:

在阅读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(),并没有发现任何并发调用那里。

tgdavies:

每个调用hasAnnotatedMethods都有自己的情况found,所以从上下文中hasAnnotatedMethods被称为无所谓。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章