天天看點

EventBus的了解EventBus深入了解

EventBus深入了解

1. 成員變量

  • private final Map<Class<?>, CopyOnWriteArrayList> subscriptionsByEventType;

    掃描注冊的對象中的所有方法,并将對象與比對的方法存儲在Subscription中,将注冊的類與其CopyOnWriteArrayList存儲在以下Map中。

  • Subscription:目前注冊對象與其中的觀察者函數,資料結構:

    final Object subscriber;

    final SubscriberMethod subscriberMethod;

  • SubscriberMethod

    将掃描到的含有注釋

    @Subscribe

    的函數封裝為SubscriberMethod,資料結構如下:

    final Method method; final ThreadMode threadMode; final Class<?> eventType; (監聽的事件類型) final int priority; final boolean sticky;

  • private final Map<Object, List<Class<?>>> typesBySubscriber;

    存儲每個注冊過的對象中監聽了的所有事件類型

2. register(Object subscriber)

  • EventBus.getDefault().register(this);

    EventBus.getDefault()是一個單例,實作如下:

public static EventBus getDefault() {  
		       if (defaultInstance == null) {  
		           synchronized (EventBus.class) {  
		               if (defaultInstance == null) {  
		                   defaultInstance = new EventBus();  
		               }  
		           }  
		       }  
		       return defaultInstance;  
		   } 
           
  • 調用順序

    register(Object subscriber) -> subscriberMethodFinder.findSubscriberMethods(subscriberClass) -> subscribe(subscriber, subscriberMethod);

  • findSubscriberMethods

    掃描函數目前對象中符合條件的函數,将掃描到的函數傳入FindState中,經過校驗後存儲于FindState的subscriberMethods中。

    掃描規則:

    • 函數非靜态,抽象函數;
    • 函數為Public;
    • 函數僅單個參數;
    • 函數擁有

      @Subscribe

      的注解
  1. FindState:為掃描到的函數做校驗,在校驗後,釋放自己持有的資源。第一層校驗在checkAdd函數中,如果目前尚未有函數監聽過目前事件,就直接跳過第二層檢查。第二層檢查為完整的函數簽名的檢查,将函數名與監聽事件類名拼接作為函數簽名,如果目前subscriberClassByMethodKey中不存在相同methodKey時,傳回true,檢查結束;若存在相同methodKey時,說明子類重寫了父類的監聽函數,此時應當保留子類的監聽函數而忽略父類。由于掃描是由子類向父類的順序,故此時應當保留methodClassOld而忽略methodClass。
    boolean checkAdd(Method method, Class<?> eventType) {
                // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
                // Usually a subscriber doesn't have methods listening to the same event type.
                Object existing = anyMethodByEventType.put(eventType, method);
                if (existing == null) {
                    return true;
                } else {
                    if (existing instanceof Method) {
                        if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                            // Paranoia check
                            throw new IllegalStateException();
                        }
                        // Put any non-Method object to "consume" the existing Method
                        anyMethodByEventType.put(eventType, this);
                    }
                    return checkAddWithMethodSignature(method, eventType);
                }
            }
    
            private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
                methodKeyBuilder.setLength(0);
                methodKeyBuilder.append(method.getName());
                methodKeyBuilder.append('>').append(eventType.getName());
    
                String methodKey = methodKeyBuilder.toString();
                Class<?> methodClass = method.getDeclaringClass();
                Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
                if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                    // Only add if not already found in a sub class
                    return true;
                } else {
                    // Revert the put, old class is further down the class hierarchy
                    subscriberClassByMethodKey.put(methodKey, methodClassOld);
                    return false;
                }
            }
               
  2. subscribe(subscriber, subscriberMethod)
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    	        Class<?> eventType = subscriberMethod.eventType;
    	        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;
    	            }
    	        }
    
    	        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    	        if (subscribedEvents == null) {
    	            subscribedEvents = new ArrayList<>();
    	            typesBySubscriber.put(subscriber, subscribedEvents);
    	        }
    	        subscribedEvents.add(eventType);
    
    	    }
               

    在進行非空校驗以及确定newSubscription尚未被添加至subscriptionsByEventType後,根據優先級将newSubscription插入subscriptionsByEventType的對應eventType的list中。

    typesBySubscriber維護一個鍵為注冊的對象,值為該對象中所監聽的事件類型的List,根據subscriber拿到list,并将新掃描得到的eventType加入。

3. post(Object event)

```
	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;
            }
        }
    }
```
           
  • currentPostingThreadState是一個ThreadLocal類型的,裡面存儲了PostingThreadState;PostingThreadState包含了一個eventQueue和一些标志位。
    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {  
    		       @Override  
    		       protected PostingThreadState initialValue() {  
    		           return new PostingThreadState();  
    		       }  
    		   }  
               
  • 把傳入的event,儲存到了目前線程中的一個變量PostingThreadState的eventQueue中。判斷目前是否是UI線程,周遊隊列中的所有的event,調用postSingleEvent(ev entQueue.remove(0), postingState)方法。通過對于isPosting的判斷,防止每次post都會去調用整個隊列時,造成方法多次調用。
  • postSingleEvent
    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);
    	        }
    	        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));
    	            }
    	        }
    	    }
               

通過lookupAllEventTypes(eventClass)得到目前eventClass的Class,以及父類和接口的Class類型,而後逐個調用postSingleEventForEventType方法。

  • postSingleEventForEventType
    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    		        CopyOnWriteArrayList<Subscription> subscriptions;
    		        synchronized (this) {
    		            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;
    		    }
               
    從subscriptionsByEventType中拿到目前eventClass的List ,周遊,通過postToSubscription判斷執行線程,逐個調用。
  • postToSubscription
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
               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 {
                           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);
               }
           }
               
    根據threadMode去判斷應該在哪個線程去執行該方法,而invokeSubscriber方法内通過反射調用函數。
    • MainThread:

      首先去判斷目前如果是UI線程,則直接調用;否則, mainThreadPoster.enqueue(subscription, event);把目前的方法加入到隊列,然後通過handler去發送一個消息,在handler的handleMessage中,去執行方法。

    • BackgroundThread:

      如果目前非UI線程,則直接調用;如果是UI線程,則将任務加入到背景的一個隊列,最終由Eventbus中的一個線程池去逐個調用

      executorService = Executors.newCachedThreadPool()。

    • Async:

      将任務加入到背景的一個隊列,最終由Eventbus中的一個線程池去調用;線程池與BackgroundThread用的是同一個,會動态控制并發。

4. EventBus的線程池

BackgroundThread和Async的主要差別:

  1. BackgroundThread會判斷是否是主線程,是主線程會調用線程池來解決,不是主線程則直接在BackgroundThread目前線程中調用;而Async都會線上程池中調用。
  2. BackgroundThread的任務會線上程池中順序執行,而Async在沒有限制。

    1) AsyncPoster

    public void enqueue(Subscription subscription, Object event) {
    	        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    	        queue.enqueue(pendingPost);
    	        eventBus.getExecutorService().execute(this);
    	    }
    
    	    @Override
    	    public void run() {
    	        PendingPost pendingPost = queue.poll();
    	        if(pendingPost == null) {
    	            throw new IllegalStateException("No pending post available");
    	        }
    	        eventBus.invokeSubscriber(pendingPost);
    	    }
               
    eventBus.getExecutorService()獲得如下線程池:
    private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
               

    在enqueque()中入隊并執行目前run(),從隊列擷取到pendingPost并發執行。

    PendingPostQueue為連結清單結構,入隊出隊黨閥均為同步方法,為保證并發執行時,單個PendingPost不會被執行多次。

    synchronized PendingPost poll() {
            PendingPost pendingPost = head;
            if (head != null) {
               head = head.next;
               if (head == null) {
                    tail = null;
               }
            }
            return pendingPost;
       }
               
    2)BackgroundPoster
    public void enqueue(Subscription subscription, Object event) {
            PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
            synchronized (this) {
                queue.enqueue(pendingPost);
                if (!executorRunning) {
                    executorRunning = true;
                    eventBus.getExecutorService().execute(this);
                }
            }
        }
        @Override
        public void run() {
            try {
                try {
                    while (true) {
                        PendingPost pendingPost = queue.poll(1000);
                        if (pendingPost == null) {
                            synchronized (this) {
                                // Check again, this time in synchronized
                                pendingPost = queue.poll();
                                if (pendingPost == null) {
                                    executorRunning = false;
                                    return;
                                }
                            }
                        }
                        eventBus.invokeSubscriber(pendingPost);
                    }
                } catch (InterruptedException e) {
                    eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
                }
            } finally {
                executorRunning = false;
            }
        }
               
    通過executorRunning和同步鎖保證任何時刻僅有一個線程在執行,僅當抛出異常或隊列取空後,置executorRunning為false,才能新開線程,實作了 BackgroundThread的任務線上程池中順序執行。

5. 粘性事件

  1. 設計初衷:事件的發出早于觀察者的注冊,EventBus将粘性事件存儲起來,在觀察者注冊後,将其發出。
    資料結構:private final Map<Class<?>, Object> stickyEvents;
     		儲存每個Event類型的最近一次post出的event
               
  2. postSticky
    public void postSticky(Object event) {
       	        synchronized (stickyEvents) {
       	            stickyEvents.put(event.getClass(), event);
       	        }
       	        // Should be posted after it is putted, in case the subscriber wants to remove immediately
       	        post(event);
       	    }
               
    将粘性事件儲存在stickyEvents,而後post出,此時如果存在已經注冊的觀察者,則情況同普通事件情況相同;如尚無注冊的觀察者,在postSingleEvent函數中将時間轉化為一個NoSubscriberEvent事件發出,可由EventBus消耗并處理。待觀察者注冊時,從stickyEvents中将事件取出,重新分發給注冊的觀察者。
  3. register
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    		        Class<?> eventType = subscriberMethod.eventType;
    		        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;
    		            }
    		        }
    	
    		        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);
    		            }
    		        }
    		    }
    	
               
    在 if (subscriberMethod.sticky)這段代碼中,首先判斷是否監聽Event的子類,而後調用checkPostStickyEventToSubscription将黏性事件發出,在checkPostStickyEventToSubscription中,判空後按一半事件的post流程将事件傳遞給觀察者。
    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
    		        if (stickyEvent != null) {
    		            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
    		            // --> Strange corner case, which we don't take care of here.
    		            postToSubscription(newSubscription, stickyEvent, isMainThread());
    		        }
    		    }