greenrobot / EventBus

Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
http://greenrobot.org/eventbus/
Apache License 2.0
24.69k stars 4.66k forks source link

When does `postingState.isPosting` become false in the `post(Object event)` method? #669

Open sreramk opened 3 years ago

sreramk commented 3 years ago

The variable postingState is local to the thread retrieving it. https://github.com/greenrobot/EventBus/blob/1d995077d0b620a6aae9c60a8b96443113752305/EventBus/src/org/greenrobot/eventbus/EventBus.java#L260

Therefore, it must always be unique to each concurrent (or parallel) thread running the same method.

When does the value of the if statement become false in the above condition? Assuming it does become false, why doesn't this cause any race conditions? Given that there are no locks used, and it is also not an atomic variable.

andob commented 3 years ago

as far as I understand the code:

When does the value of the if statement become false in the above condition? before the if statement isPosting will always be false. seems like a safeguard.

Assuming it does become false, why doesn't this cause any race conditions? well it probably would cause race conditions in that case.

however, if you look at cancelEventDelivery you'll see this variable is used in order to ensure some preconditions. so it's not useless.

sreramk commented 3 years ago

Thanks for clarifying. I was trying to understand the code and that part was confusing. Even if it does not have any performance impact, removing the condition statement (assuming there is no other reason for having it) could make that part less confusing.

tomridder commented 1 year ago

Thanks for clarifying. I was trying to understand the code and that part was confusing. Even if it does not have any performance impact, removing the condition statement (assuming there is no other reason for having it) could make that part less confusing.

race condition will appear with shared variable ,but PostingThreadState variable is in ThreadLocal.so it is unique for every thread , not a shared variable. so it won't cause race condition.