Skip to content

Instantly share code, notes, and snippets.

@barinek
Created February 26, 2018 03:02
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 barinek/9007bb6d4c47ac776fb23d1d2bb14e48 to your computer and use it in GitHub Desktop.
Save barinek/9007bb6d4c47ac776fb23d1d2bb14e48 to your computer and use it in GitHub Desktop.
class CircuitBreaker(val timeoutInMillis: Long = 200, val maxFailures: Int = 3, val retryIntervalInMillis: Long = 300) {
fun <T> withCircuitBreaker(function: () -> T, fallback: () -> T): T {
if (open() && !shouldRetry()) return fallback()
val future = Executors.newSingleThreadExecutor().submit(function)
return try {
future.get(timeoutInMillis, TimeUnit.MILLISECONDS).apply {
reset()
}
} catch (e: Exception) {
fail()
fallback()
} finally {
future.cancel(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment