kotlinx-rpc icon indicating copy to clipboard operation
kotlinx-rpc copied to clipboard

Memory leak

Open ponktacology opened this issue 5 months ago • 1 comments

Describe the bug The RPC services are leaking memory. In the example below the Args and Response objects are never cleared by the GC.

To Reproduce Steps to reproduce the behavior:

Example code:

@Serializable
data class Args(val name: String)
@Serializable
data class Response(val response: String)
interface TestService : RPC {
    suspend fun test(args: Args): Response
}
object TestServer {

    class TestServiceImpl(override val coroutineContext: CoroutineContext) : TestService {
        override suspend fun test(args: Args): Response {
            return Response("Hello ${args.name} back")
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        embeddedServer(
            Netty,
            host = "0.0.0.0",
            port = 1337
        ) {
            install(RPC) {
                serialization {
                    json()
                }
            }
            routing {
                rpc("/test") {
                    registerService<TestService> { ctx -> TestServiceImpl(ctx) }
                }
            }
        }.start(true)
    }
}
object TestClient {

    @JvmStatic
    fun main(args: Array<String>) {
        runBlocking {
            val ktorClient = HttpClient(CIO) {
                install(WebSockets)
            }
            val client = ktorClient.rpc {
                url {
                    host = "0.0.0.0"
                    port = 1337
                    encodedPath = "/test"
                }
                rpcConfig {
                    serialization {
                        json()
                    }
                }
            }
            val service = client.withService<TestService>()
            var i = 0
            while (true) {
                val response = service.test(Args("Name #${i++}"))
                println(response)
                delay(1)
            }
        }
    }
}

Expected behavior No memory leaks

Additional context Inspected with VisualVM, even after the GC Args and Response objects stay in the memory and the process eventually throws OutOfMemory

ponktacology avatar Sep 24 '24 15:09 ponktacology