Skip to content

Instantly share code, notes, and snippets.

@techyourchance
Created December 21, 2019 10:41
Show Gist options
  • 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

Miha-x64 commented May 6, 2020

isFreeAndBecomeBusy name is misleading. What about tryBecomeBusy of becomeBusyIfFree?
assertNotBusyAndBecomeBusy is very long. What about forceMakeBusy?

@BeQuietLee
Copy link

isFreeAndBecomeBusy name is misleading. What about tryBecomeBusy of becomeBusyIfFree?
assertNotBusyAndBecomeBusy is very long. What about forceMakeBusy?

Agree!

@techyourchance
Copy link
Author

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?

@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