Created
February 26, 2018 03:02
-
-
Save barinek/9007bb6d4c47ac776fb23d1d2bb14e48 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
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