Skip to content

domgew/kop

Repository files navigation

KOP - Kotlin Object Pool

Maven Central Latest Tag Publish Test Kotlin Licence: MIT

KOP is a Kotlin Multiplatform object pool.

Installation

dependencies {
    // ...

    implementation("io.github.domgew:kop:<current_version>")

    // OR just for JVM:
    implementation("io.github.domgew:kop-jvm:<current_version>")

    // ...
}
repositories {
    mavenCentral()

    // ...
}

Documentation

See Dokka-generated docs.

Targets

Supported Targets:

  • JVM
  • JS: Browser
  • JS: NodeJS
  • wasmJS: Browser
  • wasmJS: NodeJS
  • Native: Linux X64
  • Native: Linux ARM64
  • Native: macOS X64
  • Native: macOS ARM64
  • Native: mingw X64
  • Native: iOS X64
  • Native: iOS ARM64
  • Native: watchOS X64
  • Native: watchOS ARM64
  • Native: tvOS X64
  • Native: tvOS ARM64

Potential Future Targets:

  • Native: Android X64
  • Native: Android ARM64

Examples

Kedis - Kotlin Multiplatform Redis Cache

val objectPool = KotlinObjectPool(
    KotlinObjectPoolConfig(
        maxSize = 4,
        keepAliveFor = 1.minutes,
        strategy = KotlinObjectPoolStrategy.LIFO,
        instanceCreator = ::createKedisClient,
    ),
)

suspend fun getValueWithCache() =
    objectPool.withObject { kedisClient: KedisClient ->
        if (!kedisClient.isAvailable()) {
            // logging might be nice
            return@withObject getExpensiveValue()
        }

        val value = kedisClient.get("testKey")

        if (value != null) {
            return@withObject value
        }

        val valueFromCostlySystem = getExpensiveValue()

        try {
            kedisClient.set(
                key = "testKey",
                value = valueFromCostlySystem,
                options = SetOptions(
                    expire = SetOptions.ExpireOption.ExpiresInSeconds(
                        seconds = 120,
                    ),
                ),
            )
        } catch (th: Throwable) {
            // ignore exception but ensure the coroutine scope is still active - probably logging would be nice
            ensureActive()
        }

        return@withObject valueFromCostlySystem
    }

suspend fun getExpensiveValue(): String =
    "Hello World!"

suspend fun createKedisClient() =
    KedisClient.newClient(
        KedisConfiguration(
            endpoint = KedisConfiguration.Endpoint.HostPort(
                host = "127.0.0.1",
                port = 6379,
            ),
            authentication = KedisConfiguration.Authentication.NoAutoAuth,
            connectionTimeoutMillis = 250,
            keepAlive = true,
        ),
    )

suspend fun KedisClient.isAvailable(): Boolean {
    if (isConnected) {
        return true
    }

    try {
        connect()
        return true
    } catch (th: Throwable) {
        ensureActive()
        return false
    }
}

About

Kotlin Multiplatform Object Pool

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages