EventBus源码分析

本文深入解析了Android中EventBus的工作原理,包括事件订阅与发布的流程、黏性事件处理机制及其实现细节。通过源码分析,揭示了EventBus如何简化组件间的通信。

###1、概述
EventBus官方定义是Android和java发布/订阅事件总线。eventbus简化组件之间的通讯,将事件发送和接收着分离,避免复杂且容易的依赖关系和生命周期,支持黏性事件。

###2、源码分析
EventBus分为事件发布者和订阅者,先从事件订阅者分析。我们在使用EventBus时通过EventBus.getDefualt()获取EventBus实例对象,通过regester()方法订阅事件。

 public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new      EventBus();
            }
        }
    }
    return defaultInstance;
}

获取EventBus通过单例双检查机制获取实例对象,获取EventBus对象后通过register方法注册事件,

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

在register方法中获取当前注册者class对象,然后通过SubsrciberMethodFinder对象通过反射获取class对象中注解方法,在register方法中通过调用subscribeMethodFinder.findSubscriberMethods方法获取注解方法

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;
    }
}

在findSubscriberMethods中先通过Method_Cache查找是否已经有缓存,Method_Cache是一个Map对象,key为注册class对象,value为SubscribleMeMethod对象,有缓存返回缓存中SubscriberMetod集合,没有通过反射获取注册者中被订阅的方法

	private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != 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.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

在通过findUsingInfo方法查找注册者订阅方法时,EventBus会创建FindState对象,通过FindState辅助查找当前注册对象获者当前父类中订阅的方法,在EventBus中创建一个大小为4的FindState集合,在findUsingInfo中获取findState对象判断当前集合中是否有可以复用的FindState对象,没有创建FindState对象放入FindState集合中,通过调用findUsingReflectionInSingleClass方法

	private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // This is faster than getMethods, especially when subscribers are fat classes like Activities
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        int modifiers = method.getModifiers();
        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()));
                    }
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException("@Subscribe method " + methodName +
                        "must have exactly 1 parameter but has " + parameterTypes.length);
            }
        } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}

在findUsingReflectionInSingleClass方法中获取订阅者中所有的方法,判断方法的修饰符和方法参数,如果当前方法中有一个事件类型参数判断当前方法是否有@Subscribe注解,如果有Subscribe注解获取注解中线程模式、是否支持黏性事件、事件类型组装一个SubscribeMetod对象存储FindState字段中,返回到regster中,获取到SubscribeMetod后,遍历SubscribeMethod集合,通过过调用subscribe方法传入当前订阅者和订阅者中有Subscribe方法的集合,在Subscribe中创建一个Subscription对象存储订阅者和SubscribeMethod对象,放入subscriptionsByEventType集合中,创建一个typeBySubscriber map集合存储被订阅者对象和订阅事件类型,然后判断是否有黏性事件接受订阅,在接受黏性事件时判断继承中订阅方法,通过调用checkPostStictyEventToSubscription接受黏性事件,通过stictyEvent中获取黏性事件,通过反射调用订阅者中@Subscribe方法。

 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);
        }
    }
}

在分析post中的方法,在post中我们通过发射事件类型对象,在post通过Thread中TheadLoaclMap获取ThreadLoacl 存储PostingThreadState对象,把当前event事件加入队列中,判断队列是否正在运行,没有运行遍历队列通过调用postSingleEvent方法,处理事件发送,在postSingleEvent中通过subscriptionsByEventType获取在register中封装的subsciptions集合,遍历集合通过调用postToSubscription方法调用method.invoke方法,在postToSubscription中判断订阅者中@Subsrcibe注解方法线程,如果是Posting就是当前post调用线程中执行,Main通过mianThreadPoster切换线程执行,Asyc通过asynPoster通过EventBus线程池做线程切换。

 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;
        }
    }
}

###3、总结
EventBus通过register注册,分为两种普通订阅和黏性订阅事件,在register中通过通过subscriberMethodFinder对象查找订阅者中订阅方法,在subscriberMethodFinder中通过FindState使用反射获取@Subscribe注解中的方法,获取方法执行线程是否黏性事件等,EventBus维护一个大小为4的FindState集合,提供重复使用,查找被注解的方法后封装成SubscriberMethod,把SubscriberMethod放到Map缓存中,下次重新打开activity或者订阅者不需要通过反射获取,当前map集合是ConcurrentHashmap保证线程安全,register查找订阅方法后把订阅对象和SubsciblerMethod存在到Subscription中,判断是否有黏性事件,如果StickEvent不为空,遍历Subsciptions集合如果eventType类型一样发射事件,用户通过post发射事件时是通过遍历register中Subscription集合,通过反射调用订阅者中方法,在subscription中存储着订阅者对象和方法。

【轴承故障诊断】基于融合鱼鹰和柯西变异的麻雀优化算法OCSSA-VMD-CNN-BILSTM轴承诊断研究【西储大学数据】(Matlab代码实现)内容概要:本文提出了一种基于融合鱼鹰和柯西变异的麻雀优化算法(OCSSA)优化变分模态分解(VMD)参数,并结合卷积神经网络(CNN)与双向长短期记忆网络(BiLSTM)的轴承故障诊断模型。该方法利用西储大学公开的轴承数据集进行验证,通过OCSSA算法优化VMD的分解层数K和惩罚因子α,有效提升信号分解精度,抑制模态混叠;随后利用CNN提取故障特征的空间信息,BiLSTM捕捉时间序列的动态特征,最终实现高精度的轴承故障分类。整个诊断流程充分结合了信号预处理、智能优化与深度学习的优势,显著提升了复杂工况下轴承故障诊断的准确性与鲁棒性。; 适合人群:具备一定信号处理、机器学习及MATLAB编程基础的研究生、科研人员及从事工业设备故障诊断的工程技术人员。; 使用场景及目标:①应用于旋转机械设备的智能运维与故障预警系统;②为轴承等关键部件的早期故障识别提供高精度诊断方案;③推动智能优化算法与深度学习在工业信号处理领域的融合研究。; 阅读建议:建议读者结合MATLAB代码实现,深入理解OCSSA优化机制、VMD参数选择策略以及CNN-BiLSTM网络结构的设计逻辑,通过复现实验掌握完整诊断流程,并可进一步尝试迁移至其他设备的故障诊断任务中进行验证与优化。
内容概要:本文档《统信服务器操作系统行业版安全加固指导》针对统信UOS(服务器行业版)操作系统,提供了全面的安全配置与加固措施,涵盖身份鉴别、访问控制、安全审计、入侵防范、可信验证和数据传输保密性六大方面。文档依据国家等级保护三级标准制定,详细列出了58项具体的安全加固项,包括账户锁定策略、密码复杂度要求、SSH安全配置、日志审计、文件权限控制、系统服务最小化、防止IP欺骗、核心转储禁用等内容,并给出了每项配置的操作命令和检查方法,旨在提升主机系统的整体安全性,满足等保合规要求。; 适合人群:系统管理员、信息安全工程师、运维技术人员以及负责统信UOS服务器部署与安全管理的专业人员;具备一定的Linux操作系统基础知识和安全管理经验者更为适宜。; 使用场景及目标:①用于统信UOS服务器系统的安全基线配置与合规性检查;②指导企业落实网络安全等级保护制度中的主机安全要求;③在系统上线前或安全整改过程中实施安全加固,防范未授权访问、信息泄露、恶意攻击等安全风险;④作为安全审计和技术检查的参考依据。; 阅读建议:建议结合实际生产环境逐步实施各项安全配置,操作前做好系统备份与测试验证,避免影响业务正常运行;同时应定期复查配置有效性,关注系统更新带来的安全策略变化,确保长期符合安全基线要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值