Skip to content

Instantly share code, notes, and snippets.

@techyourchance
Created December 21, 2019 10:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techyourchance/44670734917d4ce085224a62cb9edf81 to your computer and use it in GitHub Desktop.
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
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);
}
}
@Miha-x64
Copy link

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