Nepxion/EventBus

guava的@Subscribe的synchronized问题

MingJunDuan opened this issue · 2 comments

Hi,你好,提个问题,guava的EventBus.register()注册时,会最终调用Subscriber.create()方法,如下,会判断方法上是否有AllowConcurrentEvents注解,来创建不同的Subscriber,如果没有AllowConcurrentEvents注解则创建SynchronizedSubscriber,而这个类的invokeSubscriberMethod方法中使用了synchronized作为同步,所以如果只是加上注解Subscribe在方法上,那么非真正的并发.

...
    static Subscriber create(EventBus bus, Object listener, Method method) {
        return (Subscriber)(isDeclaredThreadSafe(method) ? new Subscriber(bus, listener, method) : new Subscriber.SynchronizedSubscriber(bus, listener, method));
    }
...
    private static boolean isDeclaredThreadSafe(Method method) {
        return method.getAnnotation(AllowConcurrentEvents.class) != null;
    }

    @VisibleForTesting
    static final class SynchronizedSubscriber extends Subscriber {
        private SynchronizedSubscriber(EventBus bus, Object target, Method method) {
            super(bus, target, method, null);
        }

        void invokeSubscriberMethod(Object event) throws InvocationTargetException {
            synchronized(this) {
                super.invokeSubscriberMethod(event);
            }
        }
    }
...

Nepxion Eventbus只是对Guava做了易用性的封装

了解