eventbus关键技术点分析

  前言

      之前想写一篇EventBus的源码分析,后面发现太多细节了,还有copy许多代码,再加上排版,猝,无法继续进行下去了,同时因为码字和排版消耗的时间也大大降低了实际的分析时间,就这样被终结了,后面跟同事讨论加上看其他博主写的优秀的文章,结合面试以及平时工作场景,其实我们只需要把主体流程理解清楚,重点是学习该框架中使用到的一些技术点,如apt,注解,线程切换等等。

     同时也说明一点,有些同学再阅读的源码的同时也想自己照着实现一遍,这样能大大提高自己的抽象能力,但是实际进行下来是一个很耗时的方式,所以这里也算是一种源码阅读与学习方式吧,关注核心,不要浪费无谓的时间在每一个细节上,这样会大大降低学习积极性的。

     然后是之前写的一片初级eventbus介绍篇,有兴趣的也可以看看吧

   EventBus初级流程

关键技术点

 

有利技术点

 1. 单例模式(双重锁)

   

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

 public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

 这里是3.0采用的双重锁模式来实例化EventBus对象,下面介绍下他的作用以及优缺点

作用:随处使用,方便

优点:既支持延迟加载、又支持高并发,使用volatile关键字解决低版本jdk指令重排序的问题

缺点:EventBus的构造方法没有设置为private,外部可以实例话,容易产生对象错误,造成bug,代码量多了些(好像可以忽略)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值