Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active August 16, 2019 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pathikrit/726a491de67a79a9c22a479a8f6552a9 to your computer and use it in GitHub Desktop.
Save pathikrit/726a491de67a79a9c22a479a8f6552a9 to your computer and use it in GitHub Desktop.
Boolean Monitor
import java.util.concurrent.TimeUnit
import scala.concurrent.duration.Duration
import com.google.common.util.concurrent.Monitor
class BooleanMonitor(monitor: Monitor = new Monitor())(check: => Boolean) {
private val guard = new Monitor.Guard(monitor) { override def isSatisfied = check }
def whenSatisfied[U](timeout: Duration = Duration.Inf)(f: => U): U = {
if (timeout.isFinite()) {
monitor.enterWhen(guard, timeout.toMillis, TimeUnit.MILLISECONDS)
}
else {
monitor.enterWhen(guard)
}
try {
f
}
finally {
monitor.leave()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment