Created
December 21, 2019 10:41
-
-
Save techyourchance/44670734917d4ce085224a62cb9edf81 to your computer and use it in GitHub Desktop.
Base class for Java Observable which needs to be aware of whether it's "busy" and expose this information to its clients
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class BaseBusyObservable<LISTENER_CLASS> extends BaseObservable<LISTENER_CLASS> { | |
private final AtomicBoolean mIsBusy = new AtomicBoolean(false); | |
public final boolean isBusy() { | |
return mIsBusy.get(); | |
} | |
/** | |
* Atomically assert not busy and become busy | |
* @throws IllegalStateException if wasn't busy when this method was called | |
*/ | |
protected final void assertNotBusyAndBecomeBusy() { | |
if (!mIsBusy.compareAndSet(false, true)) { | |
throw new IllegalStateException("assertion violation: mustn't be busy"); | |
} | |
} | |
/** | |
* Atomically check whether not busy and become busy | |
* @return true if was "free" when this method was called; false if was busy | |
*/ | |
protected final boolean isFreeAndBecomeBusy() { | |
return mIsBusy.compareAndSet(false, true); | |
} | |
/** | |
* Unconditionally become not busy | |
*/ | |
protected final void becomeNotBusy() { | |
mIsBusy.set(false); | |
} | |
} |
isFreeAndBecomeBusy
name is misleading. What abouttryBecomeBusy
ofbecomeBusyIfFree
?
assertNotBusyAndBecomeBusy
is very long. What aboutforceMakeBusy
?
Agree!
Hey folks, thanks for your input.
As we all know, naming is difficult. I tried multiple different names before I settled on this scheme. It's ugly, I'm not going to dispute that, but these names explicitly describe the functionality, and that's why I decided to stick with them.
@Miha-x64, how isFreeAndBecomeBusy
misleading exactly? What would you expect this method to do based on its current name?
Well, isFreeAndBecomeBusy
means either “tell me whether it's free and able to become busy (return get()
)”, or “become busy forcibly and tell me whether it was free (return getAndSet(true)
)”.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
isFreeAndBecomeBusy
name is misleading. What abouttryBecomeBusy
ofbecomeBusyIfFree
?assertNotBusyAndBecomeBusy
is very long. What aboutforceMakeBusy
?