Eventbus source Reading (ii)--poster

Source: Internet
Author: User
Tags eventbus

The previous section stopped at the Posttosubscription method after reading the Eventbus message:

    Private voidPosttosubscription (Subscription Subscription, Object event,Booleanismainthread) {        Switch(subscription.subscriberMethod.threadMode) { CasePosting:invokesubscriber (subscription, event);  Break;  CaseMAIN:if(ismainthread) {invokesubscriber (subscription, event); } Else{mainthreadposter.enqueue (subscription, event); }                 Break;  CaseBACKGROUND:if(ismainthread) {backgroundposter.enqueue (subscription, event); } Else{invokesubscriber (subscription, event); }                 Break;  CaseASYNC:asyncPoster.enqueue (subscription, event);  Break; default:                Throw NewIllegalStateException ("Unknown thread mode:" +Subscription.subscriberMethod.threadMode); }    }

In different modes, the current method is called in different threads, and different poster are used. The last time did not delve into this point, today to a cursory look.

From the above code, we can see that in addition to the direct execution method Invokesubscriber (subscription, event), there are several special poster, respectively, Mainthreadposter, Backgroundposter, and Asyncposter.

We come to one by one to read.

  The Mainthreadposter class is called Handlerposter, and the code is not long, with a total of 80来 rows.

  

Final classHandlerposterextendsHandler {Private Finalpendingpostqueue queue; Private Final intMaxmillisinsidehandlemessage; Private FinalEventbus Eventbus; Private Booleanhandleractive; Handlerposter (Eventbus Eventbus, Looper Looper,intmaxmillisinsidehandlemessage) {        Super(Looper);  This. Eventbus =Eventbus;  This. Maxmillisinsidehandlemessage =Maxmillisinsidehandlemessage; Queue=NewPendingpostqueue (); }    voidEnqueue (Subscription Subscription, Object event) {pendingpost pendingpost=pendingpost.obtainpendingpost (subscription, event); synchronized( This) {queue.enqueue (pendingpost); if(!handleractive) {handleractive=true; if(!SendMessage (Obtainmessage ())) {                    Throw NewEventbusexception ("Could not send Handler message"); } }} @Override Public voidhandlemessage (Message msg) {Booleanrescheduled =false; Try {            Longstarted =Systemclock.uptimemillis ();  while(true) {pendingpost pendingpost=Queue.poll (); if(Pendingpost = =NULL) {                    synchronized( This) {                        //Check again, this time in synchronizedPendingpost =Queue.poll (); if(Pendingpost = =NULL) {handleractive=false; return;                }}} eventbus.invokesubscriber (Pendingpost); LongTimeinmethod = Systemclock.uptimemillis ()-started; if(Timeinmethod >=maxmillisinsidehandlemessage) {                    if(!SendMessage (Obtainmessage ())) {                        Throw NewEventbusexception ("Could not send Handler message"); } Rescheduled=true; return; }            }        } finally{handleractive=rescheduled; }    }}

You can see that Handlerposter inherited the handler. Method Enqueue has done two things mainly.

One, place the event request into the queue of request queues.

Second, send a message to Mainlooper.

Whenever Handlerposter sends a message, the handlemessage in it will begin to work. Eventbus set the maximum working time for it. During business hours, the program continuously poll requests from the queue, executes it in the main thread until the queue is empty, or reaches the maximum working time before it ends. We can see that handlerposter is actually the message sent to do the processing, through the handler, put it in Mainthread to execute.

Backgroundposter:

Backgroundposter is the implementation of the Runnable interface.

Final classBackgroundposterImplementsRunnable {Private Finalpendingpostqueue queue; Private FinalEventbus Eventbus; Private volatile Booleanexecutorrunning; Backgroundposter (Eventbus eventbus) { This. Eventbus =Eventbus; Queue=NewPendingpostqueue (); }     Public voidEnqueue (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 voidrun () {Try {            Try {                 while(true) {pendingpost pendingpost= Queue.poll (1000); if(Pendingpost = =NULL) {                        synchronized( This) {                            //Check again, this time in synchronizedPendingpost =Queue.poll (); if(Pendingpost = =NULL) {executorrunning=false; return;                }}} eventbus.invokesubscriber (Pendingpost); }            } Catch(interruptedexception e) {LOG.W ("Event", Thread.CurrentThread (). GetName () + "was interruppted", E); }        } finally{executorrunning=false; }    }}

The Backgroundposter also maintains a request queue. Unlike Handlerposter, it no longer uses a message to initiate the execution of a task. Instead of Eventbus.getexecutorservice (). Execute (this), this method can be traced back to the Default_executor_service in Eventbusbuilder Executors.newcachedthreadpool (); in other words, the tasks performed in Backgroundposter must not be in the main thread. Another point that differs from Handlerposter is that Backgroundposter has no maximum working time, but it has a maximum wait time of--1000ms. If the queue is empty, after waiting for 1000ms, there is still no new event join in the queue, indicating that the event request has been fully executed.

Asyncposter:

The implementation of Asyncposter is the simplest, and its function is that it cannot be currently in any thread, and will certainly open a new thread to perform this task.

  

classAsyncposterImplementsRunnable {Private Finalpendingpostqueue queue; Private FinalEventbus Eventbus; Asyncposter (Eventbus eventbus) { This. Eventbus =Eventbus; Queue=NewPendingpostqueue (); }     Public voidEnqueue (Subscription Subscription, Object event) {pendingpost pendingpost=pendingpost.obtainpendingpost (subscription, event);        Queue.enqueue (Pendingpost); Eventbus.getexecutorservice (). Execute ( This); } @Override Public voidrun () {pendingpost pendingpost=Queue.poll (); if(Pendingpost = =NULL) {            Throw NewIllegalStateException ("No pending post available");    } eventbus.invokesubscriber (Pendingpost); }}

The code is relatively simple, and we can see that Asyncposter is a subtraction on backgroundposter. Thread protection was removed (because it was new), and wait was removed (also because of the new opening).

Through the above reading, we have a general understanding of the Eventbus event delivery mechanism. In the next section, we will start reading the subscription mechanism for it.

done~

Eventbus source Reading (ii)--poster

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.