Skip to content

Instantly share code, notes, and snippets.

@ronshapiro
Created April 24, 2014 13:29
Show Gist options
  • Save ronshapiro/11254606 to your computer and use it in GitHub Desktop.
Save ronshapiro/11254606 to your computer and use it in GitHub Desktop.
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
public class OneTime {
private final Semaphore mSemaphore = new Semaphore(1);
private final AtomicBoolean mWasCalled = new AtomicBoolean(false);
public void callbackOption1() {
try {
mSemaphore.acquire();
if (!mWasCalled.get()) {
doSomethingOnlyOneTime();
}
mWasCalled.set(true);
} catch (InterruptedException e) {
// propagate error
} finally {
mSemaphore.release();
}
}
public void callbackOption2() {
// must be synchronized on mWasCalled, otherwise another thread could pass the conditional
// before doSomethingOnlyOneTime() finishes.
synchronized (mWasCalled) {
if (!mWasCalled.get()) {
doSomethingOnlyOneTime();
mWasCalled.set(true);
}
}
}
private void doSomethingOnlyOneTime() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment