记录的EventBus架构中用到的技巧
大体的架构——事件总线和观察者模式,BusEvent中所有事件发放和订阅都是在一个单例中去实现的,最基础的代码结构如下,EventBus在这个基础上去优化的
public class EventCenter {
private static EventCenter instance;
private static final Object lock = new Object();
public static EventCenter getDefault() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new EventCenter();
}
}
}
return instance;
}
private ArrayList<EventListen> listens = new ArrayList<>();
public synchronized void addListen(EventListen listen) {
listens.add(listen);
}
public synchronized void removeListen(EventListen listen) {
listens.remove(listen);
}
public synchronized void post(int eventId, HashMap<String, Object> param) {
for (EventListen listen : listens) {
listen.handle(eventId, param);
}
}
public interface EventListen {
public void handle(int eventId, HashMap<String, Object> param);
}
}
1 首先EventBus是一个单例
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
2 订阅,EventBus的订阅是一个对象为订阅单位的,有效订阅方法仅为该类和父类使用@Subsrcibe标记的方法。比如,该对象中一个对象变量中使用@Subsrcibe标记的方法是没有加到订阅中的。接下来通过看整个订阅过程
传入要订阅的对象
EventBus.getDefault().register(this);
找出订阅的方法,具体分为两种。一种是通过反射找出@Subsrcibe标记的方法,一种是通过APT运行时编译的方法,先在编译代码时,就将@Subsrcibe标记的方法添加到集合中,在注册时快速找出@Subsrcibe标记的方法,省去使用反射找方法这一步,增加效率(这个技术在EventBus 3.0后加入新特性Subsrcibe Index)
关键代码:
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()) {
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;
}
}
ignoreGeneratedIndex这个变量时构建默认设置的,是否忽略新特性Subscribe Index,为false,不忽略
在这里添加缓存,避免多次重复查找(在EventBus中缓存和复用的技术用到非常非常多,FindState就是一直在复用的,避免多次重复新建对象)
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 如果不使用新特性,即为null,使用反射查找的方法
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.clazz 置null,停止
// 查找,退出循环
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
我们看使用反射查找那部分关键的代码
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
}
符合要求的方法,必须是public修饰的,而且有且仅有一个参数,为什么只能有一个方法,这是因为EventBus管理订阅的方式是通过参数区分管理,即同一个参数类型就放在同一个集合里,这样当发出这个参数的事件时,只需将这个集合遍历发放一遍即可。这样无关的订阅就不会接收到事件。
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;
}
}
到这里基本完成了订阅步骤,订阅步骤中关于集合部分的代码都是在同步代码块中的,说明EventBus支持异步的。
补充一点:黏性事件的实现也是在订阅步骤中的
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);
}
}
其实就是在黏性事件放在一个集合中,在注册时,遍历一遍,看是否有符合条件的黏性事件。
3 发送事件 主要技术点在订阅方法指定的线程内处理事件
下发订阅事件
EventBus.getDefault().post("");
在这里使用到了ThreadLocal用于获得当前下放订阅事件的线程的状态
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>(); // 当前线程未下发的信息
boolean isPosting; // 这个变量用于高优先级拦截事件时使用
boolean isMainThread; // 是否为主线程
Subscription subscription; // 当前正处理下发事件的订阅方法
Object event; // 下发的订阅事件
boolean canceled; // 该线程取消下放事件
}
下放的这个事件是只能是单个对象,通过预先配置eventInheritance变量,为true,使用继承关系。例如下放订阅对象是A继承B,如果使用使用继承关系会同时下发到监听A的方法和监听B的方法。如不使用继承关系只会下发到监听A的方法。
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);
}
// ..
}
}
然后通过优先级下发都每一个订阅的方法
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;
}
注意这个取消继续下发,个人感觉由于线程问题,使用时需要十分小心
接下就是下发订阅事件的核心代码了,按照订阅方法指定的线程下发订阅事件
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 {
// 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)POSTING
和下发订阅事件同一条线程,直接在下发事件线程通过反射处理事件
void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
(2)MAIN
在主线程下发事件,如果不在主线程,通过主线程的hander下发事件。
(3)MAIN_ORDEREN
也是在主线程下发事件与MAIN不同,直接往主线程的hander中丢,如果持有主线程未null在下发线程处理,这里作者说了有缺陷可能之后会优化
(4)BACKGROUND
如果下发线程是主线程就丢到线程池中去处理,就在不要在主线程中处理。
(5)ASYNC
不管三七二十一直接丢到线程中去处理,仔细的话就会发现BackgroundPoster和AsyncPoster这里两个类的实现其实是一样的。
还有黏性下发事件和下发事件只是多了一步
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);
}
4 记得要取消订阅,避免内存泄漏,EventBus用的全是强引用,代码只是和订阅反着来
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());
}
}
到这里EventBus架构源码解析就基本全了,源码并不多,用的想法、技术点和数据结构都挺精妙的。
里面就用到了队列的数据结构,可以学习一下
public class Queue {
private Node head;
private Node tail;
synchronized void enqueue(Node o) {
if (tail != null) {
tail.next = o;
tail = o;
} else if (head == null) {
head = tail = o;
} else {
throw new IllegalStateException("Head present, but no tail");
}
}
synchronized Node poll() {
Node node = head;
if (head != null) {
head = head.next;
if (head == null) {
tail = null;
}
}
return node;
}
public class Node {
public Node next;
public Object o;
}
}