Search code examples
kotlinkotlin-coroutinesktorthread-local

Coroutine from each request comes with a dirty ThreadLocal, Ktor 2.x.x


And I haven't found a way to replicate it.

So I have a ThreadLocal storing a Map<String,String> whose initial value is an empty map.

I'm checking at the beginning of every HTTP Request, and unpredictably that ThreadLocal may be storing a non empty map, with values from another previous request.

I'm using the following construct:

withContext(threadLocal.asContextElement(someMap)){...}

How can I fix it?


Solution

  • The parent coroutine context for all requests can be configured when starting the ktor server.

    When creating the embedded server multiple helper methods can be used. The most commonly used, however, passes an EmptyCoroutineContext, and so that one cannot be used.

    I used

    public fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration>
    CoroutineScope.embeddedServer(
        factory: ApplicationEngineFactory<TEngine, TConfiguration>,
        vararg connectors: EngineConnectorConfig = arrayOf(EngineConnectorBuilder()),
        watchPaths: List<String> = listOf(WORKING_DIRECTORY_PATH),
        parentCoroutineContext: CoroutineContext = EmptyCoroutineContext,
        configure: TConfiguration.() -> Unit = {},
        module: Application.() -> Unit
    ): TEngine
    

    insead.

    Ej:

    
     GlobalScope.embeddedServer(
                    Netty,
                    port = config.port,
                    parentCoroutineContext = myThreadLocal.asContextElement()
                ) {
                    ...
                }