Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Miha-x64 Miha-x64 commented May 6, 2020

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

@BeQuietLee

This comment has been minimized.

Copy link

@BeQuietLee BeQuietLee commented May 17, 2020

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

Agree!

@techyourchance

This comment has been minimized.

Copy link
Owner Author

@techyourchance techyourchance commented May 18, 2020

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

This comment has been minimized.

Copy link

@Miha-x64 Miha-x64 commented May 18, 2020

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
You can’t perform that action at this time.