天天看點

EventBus—源碼解析

1. EventBus 簡單使用

EventBus的使用實踐已經在上一篇的部落格中講述了,可查閱EventBus—使用實踐。

在此隻簡單列舉EventBus的使用:

1.1. 定義事件

public class TextEvent {
    private String mText;

    public TextEvent(String text) {
        this.mText = text;
    }

    public String getText() {
        return mText;
    }

    public void setText(String text) {
        this.mText = text;
    }
}
           

1.2. 注冊與解注冊

@Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
           

1.3. 釋出事件

EventBus.getDefault().post(new TextEvent("From MainActivity text event"));
           

1.4. 接收事件

@Subscribe
    public void onHandleTextEvent(TextEvent event){
        mTvResult.setText(event.getText());
    }
           

2. 源碼解析

在解析EventBus源碼之前,想想幾個問題:

  1. 通過簡單的幾行代碼,EventBus是如何找到訂閱者的?
  2. 粘性事件是怎麼實作的?
  3. EventBus是如何實作切換線程的?

EventBus所有的秘密都藏在EventBus.getDefault().register(this)方法裡面,先看看Event類關系圖:

EventBus—源碼解析

其中有幾個非常重要的資料結構需要注意,EventBus事件分發與處理都是圍繞着它們進行處理:

  • subscriptionByEventType:事件與訂閱資訊的映射關系表,一般為一對多的關系;
  • typesBySubscriber:訂閱者與事件的映射關系表,
  • stickyEvents:粘性事件存儲表,key為事件class對象,value為粘性事件對象;
  • subscriberMethodFinder:算法核心類,找尋與解析訂閱者的所有訂閱方法并封裝成SubscriberMethod傳回;
  • Poster子類:切換不同線程執行訂閱方法的輔助類;

2.1. 注冊(register)

EventBus用了典型的單例模式,先看看它的register方法做了些什麼事情:

EventBus:

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        // 擷取訂閱者的訂閱方法并封裝成SubscriberMethod傳回
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                // 将訂閱者以及訂閱方法添加到相應的映射表中
                subscribe(subscriber, subscriberMethod);
            }
        }
    }
           

SubscriberMethodFinder.findSubscriberMethods()方法中有兩個方法可以擷取subscriberMethods,分别通過反射方法或索引加速方法擷取,可通過ignoreGeneratedIndex配置修改相應的政策,預設為false。其中索引加速在第三節講述,通過開啟索引加速,極大地提升了EventBus的運作效率。反射擷取訂閱方法就不講述了,較簡單。

SubscriberMethodFinder:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
            // 反射政策方法擷取訂閱方法
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            // 索引加速方法政策,若啟用索引加速,則用索引加速政策,否則最終
            // 也會使用反射方法擷取
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            // 如果訂閱者沒有訂閱方法,即@Subscribe注解标注的方法,則會抛異常
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
    
    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 通過索引加速政策擷取subscriberInfo
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                // 若未啟用索引加速。則使用反射方法擷取
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }
    
    private SubscriberInfo getSubscriberInfo(FindState findState) {
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        // 啟動索引加速後,subscriberInfoIndexes不為null,并使用其直接擷取SubscriberInfo
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }    
    
           

再回到EventBus的register方法中調用的subscribe(subscriber, subscriberMethod)方法:

EventBus:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        // 封裝訂閱資訊Subscription,訂閱者以及其其中一個訂閱方法
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        // 擷取事件與訂閱的映射關系表中的訂閱資訊清單,若無,則重新建立一個清單
        // 事件與訂閱者是一對多的關系
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        // 将封裝的訂閱資訊根據優先級添加到關系映射表中
        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        // 建構與添加 訂閱者與事件的關系并添加到subscribedEvents映射表中
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        // 若監聽了粘性事,則執行粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super
                classes: Class -> List<Class>).
                // 周遊粘性事件的清單,并執行其中比對的粘性事件
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }
           

小結:

EventBus注冊主要做了一下幾件事:

  1. 通過SubscriberMethodFinder根據訂閱者class查找相應的訂閱方法;
  2. 周遊每個訂閱方法,把訂閱者和訂閱方法建構成Subscription;
  3. 根據優先級将Subscription添加到subscriptionsByEventType(即使用EventBus時可通過priority配置事件的處理優先級)
  4. 把訂閱者及其對應訂閱方法添加到typesBySubscriber;
  5. 執行粘性事件(重點)

2.2. 釋出事件(Post)

釋出事件其實是基于上述的幾個映射表,擷取訂閱者的訂閱方法,并利用反射執行訂閱方法,并使用了消費者與生産者模式:

EventBus:

/** Posts the given event to the event bus. */
    public void post(Object event) {
        // 擷取目前線程的事件隊列,并将新來的事件插入置隊列中
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                // 不斷分發事件,直至為空
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
    
    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                // 釋出事件
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        // 若無訂閱者訂閱該事件,則會釋出NoSubscriberEvent事件
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 關鍵點:通過subscriptionsByEventType映射清單,擷取訂閱者資訊
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 周遊所有的訂閱者并執行該事件的訂閱方法
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    // 執行訂閱者的方法
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }
    
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        // 通過訂閱方法的線程模式,使用不同的政策執行訂閱方法,通過HandlerPoster
        // AsyncPoster,BackgroundPoster執行不同的線程政策,比如背景線程、主線程等,AsyncPoster等内部使用了生産者和消費者的模式
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    // temporary: technically not correct as poster not decoupled from subscriber
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }    
           

小結:

分發事件主要做了以下幾件事情:

  1. 把事件插入到目前線程的事件隊列中,不斷周遊釋出事件隊列中的事件;
  2. 通過subscriptionsByEventType擷取每個事件的訂閱者的方法;
  3. 根據ThreadMode,并依賴HandlerPoster,AsyncPoster,BackgroundPoster執行不同的線程政策;

通過上述的分析,已經完整地解析上述的三個問題:釋出、粘性事件以及線程模式。

2.3. 解注冊(unregister)

EventBus:

/** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        //
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }
           

有了上面注冊的過程,解注冊就非常簡單了,主要做了以下幾件事件:

  1. 通過subscribedTypes擷取該訂閱者所有的訂閱事件;(subscribedTypes映射清單的作用就是擷取訂閱者訂閱的所有事件,友善解注冊)
  2. 周遊所有事件,移除subscriptionsByEventType中的訂閱者;
  3. 從subscribedTypes中移除該訂閱者;

**注意:**注冊和解注冊必要成對存在,否則将出現記憶體洩漏。

3. 索引加速

為了提供性能,EventBus 3.0引入了索引加速的功能,大幅度提高的性能。啟動索引加速需要做一些額外的配置,可參考EventBus—使用實踐。其實索引加速功能,就是利用APT方式在編譯時解析注解生成索引java檔案,避免使用反射。

回顧上面的分析,整個流程中在SubscriberMethodFinder.findSubscriberMethods()檢索訂閱方法時會使用反射進行擷取,這裡會有性能的問題,那麼索引加速在記憶體中直接加載避免使用反射擷取。

使用索引加速時會在build目錄下生成一個java檔案,例如:

EventBus—源碼解析

java檔案的名稱是在子產品gradle中配置的

defaultConfig {
        .....
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ eventBusIndex : 'com.wuzl.eventbus.TestEventBusIndex' ]
            }
        }
        .....
    }
           

看看編譯生成的索引類,将所有訂閱者及其訂閱方法全部緩存至SUBSCRIBER_INDEX中,顯然通過SUBSCRIBER_INDEX可以擷取訂閱者所有資訊,而避免使用反射,那麼接下來需要将索引檔案配置進去。

TestEventBusIndex:

public class TestEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[]{
                new SubscriberMethodInfo("handleTextEvent", com.wuzl.eventbus.event.TextEvent.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}
           

在使用索引加速的時候,需要将該索引檔案配置到EventBus當中

EventBus.builder().addIndex(new TestEventBusIndex()).installDefaultEventBus();
           

EventBus:

/** Adds an index generated by EventBus' annotation preprocessor. */
    public EventBusBuilder addIndex(SubscriberInfoIndex index) {
        if (subscriberInfoIndexes == null) {
            subscriberInfoIndexes = new ArrayList<>();
        }
        // 将索引加速類添加到subscriberInfoIndexes資料結構
        subscriberInfoIndexes.add(index);
        return this;
    }
    
    // 重新建構預設的EventBus
    public EventBus installDefaultEventBus() {
        synchronized (EventBus.class) {
            if (EventBus.defaultInstance != null) {
                throw new EventBusException("Default instance already exists." +
                        " It may be only set once before it's used the first time to ensure consistent behavior.");
            }
            // 重新new一個EventBus對象并設定為預設EventBus
            EventBus.defaultInstance = build();
            return EventBus.defaultInstance;
        }
    }
    
    EventBus(EventBusBuilder builder) {
        
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        // 将索引加速傳遞給SubscriberMethodFinder
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    }    
    
           

那麼SubscriberMethodFinder在檢索訂閱者資訊時,發現subscriberInfoIndexes不為null,将直接從記憶體中加載資訊,而不走反射流程,極大地提高的性能。

SubscriberMethodFinder:

private SubscriberInfo getSubscriberInfo(FindState findState) {
        ....
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }
           

小結:

其實索引加速做的事情很簡單,就是避免在findSubscriberMethods去調用耗時的反射機制。實作非常巧妙。

4. 總結

EventBus的源碼解析中,發現非常多有用的設計思想,比如典型的單例模式、生成者與消費者模式、FindState的緩存機制以及巧妙的APT索引加速等等,非常值得學習與借鑒。