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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
)”.