Skip to content

Commit

Permalink
Validate and retry when Ogmios is not connected
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewWestberg committed Sep 24, 2024
1 parent 731c553 commit a0c9574
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion newm-objectpool/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ if (!project.hasProperty("isGithubActions")) {
java.sourceCompatibility = JavaVersion.VERSION_21
java.targetCompatibility = JavaVersion.VERSION_21

version = "0.2.0-SNAPSHOT"
version = "0.3.0-SNAPSHOT"

ktlint {
version.set(Dependencies.KtLint.VERSION)
Expand Down
32 changes: 29 additions & 3 deletions newm-objectpool/src/main/kotlin/io/newm/objectpool/DefaultPool.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package io.newm.objectpool

import java.util.concurrent.atomic.AtomicLongFieldUpdater
import java.util.concurrent.atomic.AtomicReferenceArray
import org.slf4j.LoggerFactory

private const val MULTIPLIER = 4
private const val ATTEMPTS = 8
Expand All @@ -14,6 +15,8 @@ private const val MAX_CAPACITY = Int.MAX_VALUE / MULTIPLIER
abstract class DefaultPool<T : Any>(
final override val capacity: Int
) : ObjectPool<T> {
private val log by lazy { LoggerFactory.getLogger("DefaultPool") }

init {
require(capacity > 0) { "capacity must be > 0, but it was $capacity" }
require(capacity <= MAX_CAPACITY) {
Expand Down Expand Up @@ -48,11 +51,34 @@ abstract class DefaultPool<T : Any>(
*/
protected open suspend fun validateInstance(instance: T) {}

final override suspend fun borrow(): T = tryPop()?.let { clearInstance(it) } ?: produceInstance()
final override suspend fun borrow(): T {
var exception: Throwable? = null
repeat(ATTEMPTS) { attempt ->
try {
val instance = tryPop()?.let { popped ->
clearInstance(popped).also { validateInstance(it) }
} ?: run {
produceInstance().also { validateInstance(it) }
}
return instance
} catch (e: Throwable) {
log.warn("Failed to produce instance (attempt ${attempt + 1}). Retrying.", e)
exception = e
}
}
throw IllegalStateException("Failed to produce instance after $ATTEMPTS attempts", exception)
}

final override suspend fun recycle(instance: T) {
validateInstance(instance)
if (!tryPush(instance)) disposeInstance(instance)
try {
validateInstance(instance)
if (!tryPush(instance)) {
disposeInstance(instance)
}
} catch (e: Throwable) {
log.warn("Failed to validate instance. Disposing.", e)
disposeInstance(instance)
}
}

final override fun dispose() {
Expand Down

0 comments on commit a0c9574

Please sign in to comment.