Skip to content

Instantly share code, notes, and snippets.

@vishalratna-microsoft
Created April 8, 2022 08:41
Show Gist options
  • Save vishalratna-microsoft/ba6bd6738a913a595efd7e54b40dadf3 to your computer and use it in GitHub Desktop.
Save vishalratna-microsoft/ba6bd6738a913a595efd7e54b40dadf3 to your computer and use it in GitHub Desktop.
Code for Once
import java.util.concurrent.atomic.AtomicInteger
/**
* Construct that helps to restrict the code execution frequency to 1. It will not allow the snippet passed through the close to be executed more than once.
* The first client to execute run() will execute this and other calls to run() will not be respected till reset is called.
*/
class Once {
private val mCounter = AtomicInteger(0)
fun run(code: Closure) {
if (mCounter.compareAndSet(0, 1)) {
code.invoke()
}
}
fun isExecuted(): Boolean {
return mCounter.get() == 1
}
fun reset() = mCounter.set(0)
}
// Represents the closure. Not using default kotlin lambda here to avoid ugly looking <Function0> class generated for Java-Kotlin Compat
interface Closure {
fun invoke()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment