Created
April 24, 2014 13:29
-
-
Save ronshapiro/11254606 to your computer and use it in GitHub Desktop.
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
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